<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Go学习, 博客">
    <meta name="description" content="个人学习储备知识与经验的秘密基地">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->

<script async src="https://www.googletagmanager.com/gtag/js?id=G-KDXT8Y4CLW"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }

    gtag('js', new Date());
    gtag('config', 'G-KDXT8Y4CLW');
</script>


    <title>Go学习 | 不二博客</title>
    <link rel="icon" type="image/png" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/favicon.png">

    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/css/matery.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/css/my.css">

    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="不二博客" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">不二博客</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">不二博客</div>
        <div class="logo-desc">
            
            个人学习储备知识与经验的秘密基地
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/weiyouwozuiku" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/weiyouwozuiku" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/程序设计/golang.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Go学习</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Go/">
                                <span class="chip bg-color">Go</span>
                            </a>
                        
                            <a href="/tags/Book/">
                                <span class="chip bg-color">Book</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/" class="post-category">
                                程序设计
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-12-01
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-01-25
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    19.3k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    72 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="基本介绍">基本介绍<a class="anchor" href="#基本介绍">¶</a></h2>
<p>Go语言之父为罗伯特·格瑞史莫、罗伯·派克和肯·汤普逊.</p>
<ul>
<li>Rob Pike（罗伯·派克），早期贝尔实验室成员，参与了 Plan9 操作系统、C 编译器以及多种语言编译器的设计和实现，UTF-8 发明人之一。​</li>
<li>Robert Griesemer（罗伯特·格瑞史莫），Java 的 HotSpot 虚拟机和 Chrome 浏览器的 JavaScript V8 引擎的设计者之一。​</li>
<li>Ken Thompson（肯·汤普逊），图灵奖得主、Unix 之父以及 C 语言的发明人之一。</li>
</ul>
<h3 id="产生的原因">产生的原因<a class="anchor" href="#产生的原因">¶</a></h3>
<ul>
<li>使用c++构建软件给程序员造成严重的心智负担​</li>
<li>使用c++编写大型项目,难以忍受过长的编译时间​</li>
<li>c++对底层硬件的依赖以及编写并发/并行程序时的复杂性</li>
</ul>
<p>三位大佬决定开发一门新的语言,解决c++在工程上的痛点打造一个以编译速度快,心智负担小,简洁的并行编程为目标的新语言。</p>
<h3 id="特性">特性<a class="anchor" href="#特性">¶</a></h3>
<ul>
<li>从csp主要继承channel的概念</li>
<li>从c主要继承基本的语法</li>
<li>从Pascal主要继承包管理特性</li>
<li>创造了defer,切片,map以及原生并发等特性</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E5%AD%A6%E4%B9%A0/go%E7%89%B9%E6%80%A7.png" alt="go特性.png"></p>
<h3 id="设计哲学">设计哲学<a class="anchor" href="#设计哲学">¶</a></h3>
<h4 id="简单-少即是多">简单-少即是多<a class="anchor" href="#简单-少即是多">¶</a></h4>
<ol>
<li>每种问题提供尽量少的答案</li>
<li>隐藏复杂度在语言本身的设计之中</li>
<li>对接口保永远的兼容</li>
</ol>
<h4 id="组合-正交解耦">组合-正交解耦<a class="anchor" href="#组合-正交解耦">¶</a></h4>
<ol>
<li>通过类型嵌入,实现数据和算法的复用</li>
<li>通过接口,实现两个实体之间的解耦</li>
<li>通过channel,解耦两个并发实体之间的数据处理依赖</li>
</ol>
<h4 id="并发-原生并发">并发-原生并发<a class="anchor" href="#并发-原生并发">¶</a></h4>
<ol>
<li>在语法层面提供一些关键字来实现并发程序的设计</li>
</ol>
<h4 id="实用-面向工程">实用-面向工程<a class="anchor" href="#实用-面向工程">¶</a></h4>
<ol>
<li>实用且好用的标准库与工具链开发,测试,调试,部署,运维等环节非常方便快捷</li>
<li>非面向过程也非面向过程</li>
<li>快速的写出简洁的代码却不易阅读</li>
</ol>
<h2 id="Go语言的执行、编译">Go语言的执行、编译<a class="anchor" href="#Go语言的执行、编译">¶</a></h2>
<h3 id="编译">编译<a class="anchor" href="#编译">¶</a></h3>
<ol>
<li>词法分析：将源代码翻译成Token（Token是代码中最小的语义结构）</li>
<li>句法分析：Token序列经过处理，变成语法树（SST）</li>
<li>语义分析：类型检查、类型推断、查看类型是否匹配、函数调用内联、逃逸分析</li>
<li>中间码生成：为了处理不同平台的差异，生成中间代码（SSA）<code>export GOSSAFUNC=&lt;指定的函数名&gt;</code>然后执行go build</li>
<li>代码优化：</li>
<li>机器码生成：生成Plan9汇编代码-&gt;编译成机器码-&gt;输出.a的机器码，使用<code>go build -gcflags -S main.go</code>获取Plan9汇编</li>
<li>链接：将各个包进行链接，包括runtime</li>
</ol>
<p>go程序的入口不是main，应该是<code>runtime/rt0_XXX.s</code></p>
<p>go程序执行的启动：</p>
<ol>
<li>读取命令行参数</li>
<li>复制参数argc argv到栈上</li>
<li>初始化g0执行栈（g0是为了调度协程的而产生的一个协程，是每一个Go程序的第一个协程）</li>
<li>运行时检测
<ol>
<li>检查各种类型的长度</li>
<li>检查指针操作</li>
<li>检查结构体字段的偏移量</li>
<li>检查atomic原子操作</li>
<li>检查cas操作</li>
<li>检查栈大小是否是2的幂次</li>
</ol>
</li>
<li>参数初始化<code>runtime.args</code>
<ol>
<li>对命令行中的参数进行处理</li>
<li>参数数量赋值给argc int32</li>
<li>参数值赋值给argv **byte</li>
</ol>
</li>
<li>调度器初始化<code>runtime.schedinit</code>
<ol>
<li>全局栈空间内存分配</li>
<li>加载命令行参数到<code>os.Args</code></li>
<li>堆内存空间的初始化</li>
<li>加载操作系统环境变量</li>
<li>初始化当前系统线程</li>
<li>GC的参数初始化</li>
<li>算法初始化（map、hash）</li>
<li>设置process变量</li>
</ol>
</li>
<li>创建主协程
<ol>
<li>创建一个新的协程，执行<code>runtime.main</code></li>
<li>放入调度器等待调度</li>
</ol>
</li>
<li>初始化M
<ol>
<li>初始化一个M，用来调度主协程</li>
</ol>
</li>
<li>主协程执行主函数
<ol>
<li>执行runtime包中的init方法</li>
<li>启动GC</li>
<li>执行用户包依赖的init方法</li>
<li>执行用户主函数的<code>main.main()</code></li>
</ol>
</li>
</ol>
<h3 id="go文件的执行">go文件的执行<a class="anchor" href="#go文件的执行">¶</a></h3>
<p>go语言可以直接使用<code>go run + 相应go文件名</code>。</p>
<h4 id="应用程序入口">应用程序入口<a class="anchor" href="#应用程序入口">¶</a></h4>
<ul>
<li>必须是main包</li>
<li>必须是main方法</li>
<li>文件名不一定是main.go</li>
</ul>
<p>Go中main函数不支持任何返回值，只能使用<code>os.Exit(0)</code>这样进行返回。</p>
<p>main函数不支持传入参数，命令参数通过<code>os.Args</code>获取。</p>
<p><strong>go语言原生支持Unicode，可以处理全世界任何语言的文本。</strong></p>
<h3 id="go文件的编译">go文件的编译<a class="anchor" href="#go文件的编译">¶</a></h3>
<p><code>go build + 相应go文件名</code>，生成相应二进制可执行文件，且是静态编译，无需担心在系统库更新的时候冲突。</p>
<hr>
<h2 id="程序结构">程序结构<a class="anchor" href="#程序结构">¶</a></h2>
<h3 id="基础概念">基础概念<a class="anchor" href="#基础概念">¶</a></h3>
<p><code>main</code>定义了一个独立可执行的程序，而不是一个库。main函数是整个程序执行时的入口函数。</p>
<table>
<thead>
<tr>
<th style="text-align:center">函数</th>
<th style="text-align:center">变量</th>
<th style="text-align:center">常量</th>
<th style="text-align:center">类型</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">func</td>
<td style="text-align:center">var</td>
<td style="text-align:center">const</td>
<td style="text-align:center">type</td>
</tr>
</tbody>
</table>
<p><strong>go不需要语句或者声明的末尾添加分号，除非一行上有多条语句。编译器主动将特定符号后的换行符转换为分号。换行的位置会影响go代码的正确解析。</strong></p>
<p>不允许使用无用的局部变量。可以使用空标识符:<code>_</code>。用于语法需要变量名，但是程序逻辑不需要。</p>
<p>空表示<code>nil</code>。</p>
<p>函数和包级别的变量可以任意顺序声明，不影响调用。CPP需要提前申明。</p>
<p>go中的传值类似C++的引用传递。指针是另一个指针，但是内存指向同一块区域。</p>
<p>常量的值只能是数字、字符串、固定的布尔值。<code>const(变量名=值)</code>。</p>
<p>GO最有意思并且最新奇的特性就是对并发编程的支持。</p>
<p>Go中的指针类似C。但是不能对指针进行加减操作。<code>*p++</code>只改变变量的值，不改变指针值。</p>
<p>使用<code>godoc</code>工具可以在本地命令行阅读标准库中的文档。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">go doc package<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><code>golang.org/x/tools/cmd/goimports</code>导入工具，它可以根据需要自动添加或删除导入的包。</p>
<p>函数的右小括弧，即函数传参数是的参数列表的最后一位的右括号，可以另起一行缩进，并在最后一个参数的后面加上一个逗号，防止编译器在行尾自动插入分号而导致编译错误。例如：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">函数名<span class="token punctuation">(</span>
    变量<span class="token number">1</span>，变量<span class="token number">2</span>，
    变量<span class="token number">3</span>，
<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>自增自减是语句，不能像C++中那样使用。且符号只能放在最后。</strong><code>x=i++</code>这样的语法是错误的。</p>
<h3 id="定义变量和结构">定义变量和结构<a class="anchor" href="#定义变量和结构">¶</a></h3>
<p>变量没有显示初始化，则隐式初始化。数值为0，字符串为空。</p>
<p>var变量的时候，支持不同类型赋值，其赋值顺序为从左到右。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> b<span class="token punctuation">,</span> f<span class="token punctuation">,</span> s <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">,</span> <span class="token number">2.3</span><span class="token punctuation">,</span> <span class="token string">"four"</span> <span class="token comment">// bool, float64, string</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h4 id="定义、创建变量">定义、创建变量<a class="anchor" href="#定义、创建变量">¶</a></h4>
<p><code>var 变量名1,变量名2 变量类型</code></p>
<p>变量定义的几种等价方式</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">s <span class="token operator">:=</span> <span class="token string">""</span>  <span class="token comment">//只能用在函数内部，不能用于包变量</span>
<span class="token keyword">var</span> s <span class="token builtin">string</span>  <span class="token comment">//依赖字符串的默认初始化零值机制</span>
<span class="token keyword">var</span> s <span class="token operator">=</span> <span class="token string">""</span>  <span class="token comment">//用于多变量声明</span>
<span class="token keyword">var</span> s <span class="token builtin">string</span> <span class="token operator">=</span> <span class="token string">""</span>  <span class="token comment">//多变量多类型时使用</span>
<span class="token keyword">var</span> <span class="token punctuation">(</span> <span class="token comment">//多个包变量的声明</span>
 a<span class="token operator">=</span><span class="token string">""</span>
 b<span class="token operator">=</span><span class="token string">""</span>
<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>简短变量声明对于已经在相同语法域中声明过的变量，简短变量声明只进行赋值操作。</p>
<p><strong>简短变量声明语句中必须至少要声明一个新的变量</strong>。</p>
<p><strong>简短变量声明语句只有对已经在同级词法域声明过的变量才和赋值操作语句等价，如果变量是在外部词法域声明的，那么简短变量声明语句将会在当前词法域重新声明一个新的变量</strong>。</p>
<p><strong>包级变量的初始化顺序并不完全取决于变量的声明顺序，而取决于调用关系。</strong></p>
<h4 id="定义struct">定义struct<a class="anchor" href="#定义struct">¶</a></h4>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> 类型名 <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    数据元素 类型
<span class="token punctuation">}</span>
<span class="token keyword">var</span> 变量名 类型名<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>命名：一个名字以一个字母或者下划线开头。后面跟任意数量的字母、数字或下划线。大小写敏感。</p>
<p>在函数外部定义的包级名字，是以首字母大写命名的，则它将是导出的，可以被外部的包访问。包本身的名字一般总是用小写字母。</p>
<p>让一些聚合类型的零值具有意义，保证不管任何类型的变量总是有一个合理有效的零值状态。</p>
<p>在包级别声明的变量会在<code>main</code>入口函数执行前完成初始化，局部变量将在声明语句被执行到的时候完成初始化。</p>
<p>定义变量有两个方式：<code>var</code>和简短变量声明(<code>:=表达式</code>)。</p>
<p>简短变量声明被广泛用于大部分的局部变量的声明和初始化。 var形式的声明语句往往是用于需要显式指定变量类型地方， 或者因为变量稍后会被重新赋值而初始值无关紧要的地方。</p>
<p>简短变量声明语句中必须<strong>至少</strong>要声明一个新的变量。其中可以有不是全部的变量之前声明过，这里只是简单的赋值。</p>
<p>简短变量声明语句只有对已经在同级语法域声明过的变量才和赋值操作语句等价。变量是在外部语法域声明的，那么简短变量声明语句将在当前语法域重新声明一个新的变量。</p>
<h4 id="new函数">new函数<a class="anchor" href="#new函数">¶</a></h4>
<p>使用new函数创建变量，表达式<code>new(类型名)</code>将创建一个T型的匿名变量，初始化为相应类型的零值，返回变量地址，返回类型为相应类型的指针。</p>
<p>类型的大小为0，有可能地址相同，例如<code>struct{}</code>和<code>[0]int</code>。</p>
<p><em>请谨慎使用大小为0的类型。如果类型的大小为0，可能导致Go语言的自动垃圾回收机制有不同的行为。具体请查看<code>runtime.SetFinalizer</code>函数相关文档</em></p>
<p>new函数只是一个预定义的函数，并不是一个关键字。可以将new名字重新定义为别的类型。<strong>但是这样就会导致重定义new的空间内无法使用new函数。</strong></p>
<h3 id="输入">输入<a class="anchor" href="#输入">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">input <span class="token operator">:=</span> bufio<span class="token punctuation">.</span><span class="token function">NewScanner</span><span class="token punctuation">(</span>os<span class="token punctuation">.</span>stdin<span class="token punctuation">)</span>
input<span class="token punctuation">.</span><span class="token function">Scan</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">//读入一行，并移除行末的换行符。读入一行返回true，否则false</span>
input<span class="token punctuation">.</span><span class="token function">Text</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">//获取一行输入。</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h3 id="输出">输出<a class="anchor" href="#输出">¶</a></h3>
<p><code>fmt</code>package包含格式化输出、接收输入的函数。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">//格式化输出</span>
fmt<span class="token punctuation">.</span><span class="token function">PrintIn</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">//输出完后换行</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<table>
<thead>
<tr>
<th style="text-align:center">%d</th>
<th style="text-align:center">十进制整数</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">%x,%o,%b</td>
<td style="text-align:center">十六进制，八进制，二进制整数</td>
</tr>
<tr>
<td style="text-align:center">%f,%g,%e</td>
<td style="text-align:center">浮点数：3.141593 3.141592653589793 3.141593e+00</td>
</tr>
<tr>
<td style="text-align:center">%t</td>
<td style="text-align:center">bool</td>
</tr>
<tr>
<td style="text-align:center">%c</td>
<td style="text-align:center">Unicode码点</td>
</tr>
<tr>
<td style="text-align:center">%s</td>
<td style="text-align:center">字符串</td>
</tr>
<tr>
<td style="text-align:center">%q</td>
<td style="text-align:center">带双引号或单引号的字符或字符串</td>
</tr>
<tr>
<td style="text-align:center">%v</td>
<td style="text-align:center">变量的自然形式</td>
</tr>
<tr>
<td style="text-align:center">%T</td>
<td style="text-align:center">变量的类型</td>
</tr>
<tr>
<td style="text-align:center">%%</td>
<td style="text-align:center">字面上的百分号标志</td>
</tr>
</tbody>
</table>
<p>通常Printf格式化字符串包含多个%参数时将会包含对应相同数量的额外操作数，但是%之后的<code>[1]</code>这样的副词告诉Printf函数再一次使用第一个操作数。%后的#副词告诉Printf在用%o、%x或%X输出时生成0、0x或0X前缀。</p>
<h3 id="注释">注释<a class="anchor" href="#注释">¶</a></h3>
<p>使用<code>//</code>进行注释。</p>
<h3 id="包和文件">包和文件<a class="anchor" href="#包和文件">¶</a></h3>
<p><strong>必须导入需要的package，缺少了必要的package或者导入了不需要的package，程序都无法编译通过。</strong></p>
<p><code>import</code>语句必须要跟在文件的<code>package</code>声明之后。</p>
<p>当import的一个包路径包含多个单词时，通常只用最后的那个单词表示即可。</p>
<p>go语言通过package管理。一个package由单个目录下的一个或者多个.go源码组成。</p>
<p>每个go都以一条package声明语句开始。表明文件属于哪一个package。</p>
<p>每个包都对应一个独立的名字空间，要在外部使用函数，必须要显式声明包名。</p>
<p>如果一个名字是大写字母开头的，那么该名字是导出的。</p>
<p>包级别的常量名用大写字母开头。</p>
<p>每个源文件的包声明前的注释是包注释。通常，包注释的第一句是包功能的概要说明。如果一个文件有多个包注释，当前的文档工具会根据源文件名的先后顺序将它们链接成一个包注释。包注释很大时，通常会放到一个独立的doc.go文件中。</p>
<p>每个包都有一个全局唯一的导入路径。由构建工具进行解释。一个导入路径代表一个目录中一个或者多个Go源文件。</p>
<p>包名不一定要唯一。一个包的名字往往和包的导入路径的最后一个字段相同。</p>
<p>包的初始化首先解决包级变量的依赖顺序，然后按照包级变量声明出现的顺序依次进行初始化。如果包中含有多个源代码文件，它们将按照发给编译器的顺序进行初始化。Go语言的构建工具会首先将.go文件根据文件名排序，然后依次调用编译器编译。</p>
<p>包级别声明的变量，有初始化表达式用初始化表达式，没有的，可以创建<code>init</code>函数进行初始化工作。每个文件可以包含多个<code>init</code>函数。</p>
<p><code>init</code>函数不能被调用或者引用。在每个文件中的<code>init</code>初始化函数，在程序开始执行时按照它们声明的顺序被自动调用。</p>
<p>每个包只会被初始化一次。</p>
<p>初始化工作自下而上进行，main包最后被初始化。确保在main函数执行之前，所有依赖的包都已经完成了初始化工作。</p>
<h3 id="循环">循环<a class="anchor" href="#循环">¶</a></h3>
<h4 id="for循环">for循环<a class="anchor" href="#for循环">¶</a></h4>
<p>注意<strong>左大括号必须要和post语句在同一行</strong></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">for</span> i<span class="token operator">:=</span>初始值<span class="token punctuation">;</span>条件<span class="token punctuation">;</span>post <span class="token punctuation">{</span>
    <span class="token comment">//todo</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h4 id="range遍历">range遍历<a class="anchor" href="#range遍历">¶</a></h4>
<p><strong>python中的range是函数，而go中的range是关键词。</strong></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">for</span> a<span class="token punctuation">,</span>b<span class="token operator">:=</span><span class="token keyword">range</span> 数组<span class="token punctuation">{</span>
    <span class="token comment">//todo</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>range每次返回两个数值：索引和相应元素值，并强制处理。</p>
<h3 id="选择判断">选择判断<a class="anchor" href="#选择判断">¶</a></h3>
<p><code>if</code>可以在比较的时候进行简单语句的赋值行为，以下代码等价：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">if</span> err<span class="token operator">:=</span>r<span class="token punctuation">.</span><span class="token function">ParseForm</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>err<span class="token operator">!=</span><span class="token boolean">nil</span><span class="token punctuation">{</span>
  log<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
 <span class="token punctuation">}</span>
<span class="token comment">//等价于</span>
err <span class="token operator">:=</span> r<span class="token punctuation">.</span><span class="token function">ParseForm</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
log<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>Go语言中条件语句不需要圆括号，但是分支中必须有大括号。</strong></p>
<p>Go语言不需要显式的在每一个<code>case</code>后写<code>break</code>，语言默认执行完<code>case</code>后的逻辑语句自动退出。如果需要<em>相邻几个<code>case</code>都执行同一逻辑时，需要自己显式的写上<code>fallthrough</code>来覆盖这种默认行为。</em></p>
<p>switch不带操作对象时称为无tag switch，默认用true值代替， 然后将每个case的表达式和true值进行比较。等价switch true。</p>
<p>switch与其他语言的差异：</p>
<ul>
<li>条件表达式不限制为常量或者整数</li>
<li>单个case中，可以出现多个结果选项，使用逗号分隔</li>
<li>与C语言相反，Go不需要break来显示退出case</li>
<li>可以不设定switch之后的表达式，在此种情况下，整个switch就是多个if else相同</li>
</ul>
<p><code>continue</code>和<code>break</code>可以使用在<code>for循环</code>，<code>switch</code>，<code>select</code>中。</p>
<h3 id="生命周期">生命周期<a class="anchor" href="#生命周期">¶</a></h3>
<p>Go中返回函数中局部变量的地址是安全的。</p>
<p>一个变量的有效周期只取决于是否可达。</p>
<p>对于在包一级声明的变量来说，变量的生命周期和整个程序的运行周期是一致的。局部变量的生命周期是动态的。每次从创建一个新变量的声明语句开始，直到该变量不再被引用为止，然后变量的存储空间可能被回收。</p>
<p>编译器自动选择在栈还是堆上分配局部变量的存储空间，不取决于是var还是new，这点不同于C++。</p>
<p>当局部变量在函数退出后，依然可以通过包一级的变量找到，则称局部变量从函数中逃逸了。逃逸的变量需要额外分配内存，同时对性能的优化可能会产生细微的影响。</p>
<p>如果将执行那个短生命周期对象的指针保存到具有长生命周期的对象中，特别是保存到全局变量时，会阻止对短生命周期对象的垃圾回收，从而影响程序的性能.</p>
<h3 id="元组赋值">元组赋值<a class="anchor" href="#元组赋值">¶</a></h3>
<p>元组赋值允许同时更新多个变量的值。赋值前，赋值语句右边的所有表达式会先进行求值，然后同意更新左边对应的变量值。例如，两值互换。</p>
<p>nil可以赋值给任何指针或引用类型的变量。</p>
<h3 id="类型">类型<a class="anchor" href="#类型">¶</a></h3>
<p>一个类型声明语句创建了一个新的类型名称。即使和现有类型具有相同的底层结构，新命名的类型提供了一个方法，用来分隔不同概念的类型，它们底层类型相同也不兼容。</p>
<p>创造新的类型：<code>type 类型名字 底层类型</code>。</p>
<p>类型声明语句一般出现在包一级。<strong>如果新创建的类型名字的首字符大写，则在外部包也可以使用</strong>。</p>
<p>对于中文汉字，Unicode标志作为小写处理。因此中文的命名默认不能导出。</p>
<p>对于每一个类型T，都有一个对应的类型转换操作<code>T(x)</code>。如果T是指针类型，可能需要用小括弧包装T。前提是<strong>两个类型的底层基础类型相同或二者都是指向相同底层结构的指针类型</strong>。</p>
<p>比较运算符可以用来比较一个命名类型的变量和另一个有着相同类型的变量，或有着相同底层类型的<em>未命名</em>类型的值之间进行比较。如果这两个值有着不同的类型，则不能直接比较。</p>
<p>自定义类型的函数定义格式如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>x 自定义类型<span class="token punctuation">)</span>函数名<span class="token punctuation">(</span><span class="token punctuation">)</span> 返回类型<span class="token punctuation">{</span>
    <span class="token comment">//pass</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h3 id="作用域">作用域<a class="anchor" href="#作用域">¶</a></h3>
<p>作用域不同于生命周期。声明语句的作用域对应的是一个源代码的文本区域；它是一个编译时的属性。一个变量的生命周期是指程序运行时变量存在的有效时间段，在此时间区域内它可以被程序的其他部分引用；是一个运行时概念。</p>
<h3 id="一些常用的函数介绍">一些常用的函数介绍<a class="anchor" href="#一些常用的函数介绍">¶</a></h3>
<p>os包提供一些与操作系统交互的函数和变量。程序的命令行参数可以通过os包的Args变量获得，即：<code>os.Args</code>，返回字符串切片，语法类似python，区间左闭右开。<code>os.Args[0]</code>为命令本身名字。省略默认传入0或len()。<strong>os.Args因为第一个参数为命令本身，因此其长度会在给定参数的数量上加一</strong></p>
<p><code>gofmt</code>按照字母顺序对包名进行排列，从而格式化。</p>
<p><strong>在进行大量字符串拼接的时候使用运算符+会导致执行的代价高昂，推荐使用strings包的Join函数。</strong></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">strings<span class="token punctuation">.</span><span class="token function">Join</span><span class="token punctuation">(</span>字符串数组<span class="token punctuation">,</span>字符串拼接时的间隔符<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><code>map</code>存储了键值对的集合，对集合元素，提供常数时间的存取操作。键的选择只要能用<code>==</code>比较就行。值也可以是任意类型。例如:<code>map[键类型]值类型</code>。<code>make</code>函数创建空map，形如：<code>make(map[string]int)</code>。</p>
<p>map的迭代顺序不确定。</p>
<p>系统文件的指针：<code>*os.File</code>。</p>
<p>系统打开文件：<code>os.Open(路径)</code>，返回的第一个值是被打开的文件，其后被<code>Scanner</code>读取，返回的第二个值是内置的<code>error</code>类型的值。</p>
<p>文件关闭使用<code>文件.Close()</code>函数。</p>
<p><code>io/ioutil</code>包中的<code>ReadFile(文件名)</code>函数读取指定文件的全部内容，返回的第一个参数是数据(byte slice)，返回的第二个是错误信息。<code>string.Split(string(数据),分割标志位)</code>函数将字符串分割成子串的切片。</p>
<p>http包：<code>net/http</code>。</p>
<p><code>http.Get(url地址)</code>函数创建HTTP请求的函数。返回两个参数，包含访问得到的请求结果的结构体，是一个可读的服务器响应流。第二个是错误信息。<code>ioutil.ReadAll(数据)</code>可以读取返回的数据的相应信息，以及可能发生的错误信息。相应的流用相应的<code>Close()</code>函数进行关闭。</p>
<p>程序出现错误时使用<code>os.Exit(1)</code>。</p>
<p>获取现在系统时间，使用包<code>time</code>，<code>time.Now()</code>。</p>
<p><code>ioutil.Discard</code>输出流是一个“垃圾桶”，可以向里面写入不需要的数据。</p>
<p><code>io.Copy(拷贝目的地,拷贝源)</code>返回两个参数，第一个字节大小，第二个是错误信息。</p>
<p>在编写命令行程序时，调用<code>flag.变量</code>函数创建可选的命令行参数，例如<code>flag.Bool</code>或<code>flag.String</code>。有三个参数属性：1.命令行标志参数的名字。2.该标志位的默认值。3.该标志参数的对应的描述信息。返回指向对应命令行标志参数变量的指针，指向的是是否设置参数的bool或者替换的字符串。需要加上<code>*</code>间接引用。</p>
<p>*在使用标志参数对应的变量之前先调用flag.Parse函数，用于更新每个标志参数对应变量的值(之前是默认值)。*解析命令行参数时遇到错误，默认打印相关的提示信息。然后调用<code>os.Exit(2)</code>终止程序。</p>
<p><code>flag.Args()</code>获取非标志参数的普通命令行参数，返回一个字符串类型的slice。</p>
<p><code>strconv.ParseFloat()</code>函数可以进行字符串对浮点型数据的转换，还有类似的字符串转换函数在<code>strconv</code>包中。</p>
<p><code>unicode</code>包提供了诸多处理rune字符相关功能的函数。</p>
<p><code>unicode/utf8</code>包提供了用于rune字符序列的UTF-8编码和解码的功能。</p>
<p><code>utf8.RuneCountInString(变量名)</code>返回字符串的Unicode字符数。</p>
<p><code>utf8.DecodeRuneInString(变量名)</code>返回两个值，第一个是对应字符本身，另一个是对应字符采用UTF8编码后的编码字节数目。</p>
<p><code>strings.LastIndex(字符串,需要寻找的字符串)</code>返回相应字符串的索引，未找到返回-1。</p>
<p>将一个整数转化为字符串，一种是用<code>fmt.Sprintf</code>返回一个格式化的字符串；另一个是用<code>strconv.Itoa()</code>。</p>
<p><code>FormatInt</code>和<code>FormatUint</code>函数可以用不同进制来格式化数字。</p>
<p><code>fmt.Sprintf()</code>函数的%b、%d、%o、%x等参数提供的功能比strconv包的Format函数方便很多，还可以添加额外信息。</p>
<p>将字符串解析为整数，相应的使用strconv包的Atoi或ParseInt函数，用于解析无符号整数的ParseUint函数。ParseInt函数的第三个参数用于制定整数的大小，16表示int16,0表示int。</p>
<p>使用<code>fmt.Scanf</code>解析输入的字符串和数字。</p>
<h3 id="垃圾回收的基本思路">垃圾回收的基本思路<a class="anchor" href="#垃圾回收的基本思路">¶</a></h3>
<p>从每个包级的变量和每个当前运行函数的每一个局部变量开始，通过指针或引用的访问路径遍历，是否可以找到该变量。如果不存在这样的访问路径，则说明该变量是不可达的。即，它的存在并不会影响程序后续的计算结果。</p>
<h2 id="基础数据类型">基础数据类型<a class="anchor" href="#基础数据类型">¶</a></h2>
<p style="filter: opacity(95%);transform:scale(0.85);text-align:center;"><img src="https://math.now.sh?from=%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%5Cbegin%7Bcases%7D%5Ctext%7B%E5%9F%BA%E7%A1%80%E7%B1%BB%E5%9E%8B%7D%5Cbegin%7Bcases%7D%5Ctext%7B%E6%95%B0%E5%AD%97%7D%5C%5C%5Ctext%7B%E5%AD%97%E7%AC%A6%E4%B8%B2%7D%5C%5C%5Ctext%7B%E5%B8%83%E5%B0%94%E5%80%BC%7D%5Cend%7Bcases%7D%5C%5C%5Ctext%7B%E5%A4%8D%E5%90%88%E7%B1%BB%E5%9E%8B%7D%5Cbegin%7Bcases%7D%5Ctext%7B%E7%BB%93%E6%9E%84%E4%BD%93%7D%5C%5C%5Ctext%7B%E6%95%B0%E7%BB%84%7D%5Cend%7Bcases%7D%5C%5C%5Ctext%7B%E5%BC%95%E7%94%A8%E7%B1%BB%E5%9E%8B%7D%5Cbegin%7Bcases%7D%5Ctext%7B%E6%8C%87%E9%92%88%7D%5C%5C%5Ctext%7B%E5%88%87%E7%89%87%7D%5C%5C%5Ctext%7B%E5%AD%97%E5%85%B8%7D%5C%5C%5Ctext%7B%E5%87%BD%E6%95%B0%7D%5C%5C%5Ctext%7B%E9%80%9A%E9%81%93%7D%5Cend%7Bcases%7D%5C%5C%5Ctext%7B%E6%8E%A5%E5%8F%A3%E7%B1%BB%E5%9E%8B%7D%5Cend%7Bcases%7D%0A"></p><ul>
<li>bool,string</li>
<li>(u)int,(u)int8,(u)int16,(u)int32,(u)int64,uintptr</li>
<li>byte,rune(32位，四字节，避免了c语言中char只有一字节导致的问题)</li>
<li>float32,float64,complex64,com</li>
</ul>
<h3 id="整数">整数<a class="anchor" href="#整数">¶</a></h3>
<table>
<thead>
<tr>
<th>int8</th>
<th>int16</th>
<th>int32</th>
<th style="text-align:center">int64</th>
</tr>
</thead>
<tbody>
<tr>
<td>uint8</td>
<td>uint16</td>
<td>uint32</td>
<td style="text-align:center">uint64</td>
</tr>
</tbody>
</table>
<p>int和uint类型为32bit或者64bit。根据编译器的不同以及cpu平台的不同，并不一定。</p>
<p>Unicode字符rune类型是和int32等价的类型，通常用于表示一个Unicode码点。可以相互使用。</p>
<p>byte和uint8是等价类型。byte类型一般强调数值是一个原始的数据而不是小的整数。</p>
<p>uintptr是无符号的整数类型，没有指定具体的bit大小，但是足以容乃指针。底层编程用。</p>
<p>一个n-bit的有符号数的值域为<img src="https://math.now.sh?inline=-2%5E%7Bn-1%7D" style="filter: opacity(95%);transform:scale(0.85);text-align:center;display:inline-block;margin: 0;">到<img src="https://math.now.sh?inline=2%5E%7Bn-1%7D-1" style="filter: opacity(95%);transform:scale(0.85);text-align:center;display:inline-block;margin: 0;">。</p>
<p>一个n-bit的无符号数的值域为0到<img src="https://math.now.sh?inline=2%5E%7Bn%7D-1" style="filter: opacity(95%);transform:scale(0.85);text-align:center;display:inline-block;margin: 0;">。</p>
<p>二元运算符，在同一优先级下，使用左优先结合规则。也可以明确使用括号表示优先顺序。</p>
<p>%取模运算符的符号和被取模数的符号总是一致。</p>
<table>
<thead>
<tr>
<th style="text-align:center">&amp;</th>
<th style="text-align:center">|</th>
<th style="text-align:center">^</th>
<th style="text-align:center">&amp;^</th>
<th style="text-align:center">&lt;&lt;</th>
<th style="text-align:center">&gt;&gt;</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">AND</td>
<td style="text-align:center">OR</td>
<td style="text-align:center">XOR</td>
<td style="text-align:center">AND NOT</td>
<td style="text-align:center">左移</td>
<td style="text-align:center">右移</td>
</tr>
</tbody>
</table>
<p>在遇到的每种类型，需要保证规则的一致性。</p>
<p>移位操作bit部分必须是无符号数。</p>
<p>左/右移运算用零填充右边空缺的bit位。</p>
<p>有符号数的右移运算会使用符号位的值填充左边空缺的bit位。</p>
<p>len函数返回值为int有符号类型，这样便于循环时，作为索引。否则循环语句使用–时，无符号数会直接变成最大的整数。</p>
<p><strong>数据类型之间的转换不存在隐式转换，只能显式转换。</strong></p>
<p>类型强制转换:<code>类型(需转换的变量名)</code>。</p>
<p>任何大小的整数字面值都可以用以0来头的八进制书写，或者以0x或者0X开头的十六进制格式书写。十六进制数字可以用大写或者小写字母。</p>
<h3 id="浮点数">浮点数<a class="anchor" href="#浮点数">¶</a></h3>
<p>GO语言提供了两种精度的浮点数：<code>float32</code>(6个十进制的精度)和<code>float64</code>(15个十进制的精度)。</p>
<p>常量<code>math.MaxFloat32</code>表示float32能表示的最大数值，大约是3.4e38。</p>
<p>wi常量<code>math.MaxFloat64</code>表示float64能表示的最大数值，大约是1.8e308。</p>
<p>**通常优先使用float64，float32的累计计算误差易扩散，且能表示的正整数不是很大，当整数大于23bit能表示的范围时，float32的表示将出现误差。**例如：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> f <span class="token builtin">float32</span><span class="token operator">=</span><span class="token number">16777216</span>
fmt<span class="token punctuation">.</span><span class="token function">Print</span><span class="token punctuation">(</span>f<span class="token operator">==</span>f<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token comment">//"true"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>小数点前后的数字都有可能被省略。所以<strong>很大很小的数最好使用科学计数法，通过e或者E来指定指数部分。</strong></p>
<p>math包中提供IEEE754浮点数标准中定义的特殊值：正无穷和负无穷以及NaN。</p>
<p><code>math.IsInf(检测数,int值)</code>：检查是否是无穷数，int值Wie正数，表示检测其是否是一个正无穷，同理负数，0表示是否是无穷，不论正负。</p>
<p><code>math.IsNaN</code>：检测一个数是否是非数。</p>
<p><code>math.NaN</code>：返回一个非数对应的值。可以用其表示一个非法的值，但是测试一个结果是否非数则<em>充满风险</em>。NaN既不大于自己，也不小于自己，也不等于自己。</p>
<p>浮点数的相等比较是<em>危险的</em>，需要小心处理精度问题。</p>
<p>**一个函数返回的浮点数结果可能失败，最好做单独的标志报告。**例如：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">compute</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>value <span class="token builtin">float64</span><span class="token punctuation">,</span>ok <span class="token builtin">bool</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token comment">//...</span>
    <span class="token keyword">if</span> failed <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">,</span><span class="token boolean">false</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> result<span class="token punctuation">,</span><span class="token boolean">true</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="复数">复数<a class="anchor" href="#复数">¶</a></h3>
<p>Go语言提供两种精度的复数类型：<code>complex64</code>和<code>complex128</code>。对应float。内建的real和imag函数分别返回复数的实部和虚部。</p>
<p>复数的创建方法：<code>complex(实部,虚部)</code>。</p>
<p>如果一个浮点数或一个十进制整数后面有一个i，则构成一个实部为0的虚数。</p>
<h3 id="布尔型">布尔型<a class="anchor" href="#布尔型">¶</a></h3>
<p>两种值：true和false。</p>
<p>&amp;&amp;的优先级高于ll。(&amp;&amp;对应逻辑乘法，||对应逻辑加法)。</p>
<p>字符的检验代码可以如下编写：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">if</span> <span class="token char">'a'</span><span class="token operator">&lt;=</span>c <span class="token operator">&amp;&amp;</span> c<span class="token operator">&lt;=</span><span class="token char">'z'</span><span class="token operator">||</span>
<span class="token char">'A'</span><span class="token operator">&lt;=</span>c<span class="token operator">&amp;&amp;</span>c<span class="token operator">&lt;=</span><span class="token char">'Z'</span><span class="token operator">||</span>
<span class="token char">'0'</span><span class="token operator">&lt;=</span>c<span class="token operator">&amp;&amp;</span>c<span class="token operator">&lt;=</span><span class="token char">'9'</span><span class="token punctuation">{</span>
    <span class="token comment">//todo</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>布尔值不会隐式转换为数字值0或者1，反之亦然。必须使用一个显式的if语句辅助转换。或者自己包装成一个函数，如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">btoi</span><span class="token punctuation">(</span>b <span class="token builtin">bool</span><span class="token punctuation">)</span><span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> b<span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token number">1</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token number">0</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">itob</span><span class="token punctuation">(</span>i <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> i<span class="token operator">!=</span><span class="token number">0</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="字符串">字符串<a class="anchor" href="#字符串">¶</a></h3>
<p>Go1.10之前推荐使用<code>bytes.Buffer</code>，之后推荐使用<code>strings.Builder</code></p>
<p>一个字符串是一个<strong>不可改变</strong>的字节序列。</p>
<p>字符串可以包含任意数据，包括byte值0。</p>
<p>文本字符串通常被解释为采用UTF8编码的Unicode码点(rune)序列。</p>
<p>使用<code>utf8.RuneCountInString</code>获取字符数量。使用<code>[]byte</code>获取字节。</p>
<p>len函数返回一个字符串中的字节数目，<strong>而不是字符数</strong>，字节数目大于等于字节数目。</p>
<p>索引操作[i]返回第i个字节的字节值。</p>
<p>超出索引范围会导致panic异常。</p>
<p><strong>第i个字节并不一定是字符串的第i个字节，因为对于非ASCII字符的UTF8编码会要两个或多个字节。</strong></p>
<p>支持切片操作。</p>
<p>字符串进行运算符比较，比较结果是字符串自然编码的顺序。</p>
<p>尝试修改字符内部数据的操作是被禁止的。</p>
<p>不变形保证了两个字符串共享相同的底层数据的话是安全的，复制任意字符串代价是廉价的，字符串和对应的子字符串切片的操作也可以安全的共享相同的内存，这两种情况都没有必要分配新的内存。</p>
<table>
<thead>
<tr>
<th>转义符</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>\a</td>
<td>响铃</td>
</tr>
<tr>
<td>\b</td>
<td>退格</td>
</tr>
<tr>
<td>\f</td>
<td>换页</td>
</tr>
<tr>
<td>\n</td>
<td>换行</td>
</tr>
<tr>
<td>\r</td>
<td>回车</td>
</tr>
<tr>
<td>\t</td>
<td>制表符</td>
</tr>
<tr>
<td>\v</td>
<td>垂直制表符</td>
</tr>
<tr>
<td>\’</td>
<td>单引号</td>
</tr>
<tr>
<td>\"</td>
<td>双引号</td>
</tr>
<tr>
<td>\\</td>
<td>反斜杠</td>
</tr>
</tbody>
</table>
<p>一个十六进制的转义形式是<code>\xhh</code>，两个hh表示十六进制数字，不区分大小写。</p>
<p>一个八进制的转义形式是<code>\ooo</code>，o表示八进制数字，不能超过\377。</p>
<p>相应的十进制的范围应该是255。</p>
<p>字符串面值形式用``包裹，其中的字符串不进行转义操作。会删除回车保证所有平台上的值都是一样的。(Windows系统会把回车和换行一起放入文本文件中)。常用于编写正则表达式，HTML模板、JSON面值等。</p>
<p>可以将一个符文序列表示为一个int32序列。这种编码方式叫UTF-32或UCS-4。但是会浪费大量空间</p>
<p>UTF-8编码的每个符号编码后第一字节的高端bit位用于表示总共有多少编码个字节。UTF-8是变长编码，无法直接通过索引获取指定位置的字符。比较紧凑，完全兼容ASCII编码，可以自动同步，通过向前回溯最多两个字节就能确定当前字符编码的开始字节的位置，是前缀编码，不会出现任何歧义。没有任何字符的编码是其他字符编码的子串，或是其他编码序列的子串。与Unicode码点一致，没有嵌入NUL(0)字节，可以很好的兼容使用NUL作为字符串结尾的编程语言。</p>
<p>例如：</p>
<ul>
<li>0xxxxxxx                                                 runes 0-127</li>
<li>110xxxxx 10xxxxxx                                  128-2047</li>
<li>1110xxxx 10xxxxxx 10xxxxxx                  2048-65535</li>
<li>11110xxx 10xxxxxx 10xxxxxx 10xxxxxx  65536-0x10ffff</li>
</ul>
<p>对于小于256码点值可以写在一个十六进制转义字节中，但是对于更大的码点则必须使用\u或者\U转义形式。</p>
<p>判断一个字符串是否是另一个字符串的前缀/后缀：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">HasPrefix</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span>prefix <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">len</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token function">len</span><span class="token punctuation">(</span>prefix<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> s<span class="token punctuation">[</span><span class="token punctuation">:</span><span class="token function">len</span><span class="token punctuation">(</span>prefix<span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token operator">==</span>prefix
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">HasSuffix</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span>suffic <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">len</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token function">len</span><span class="token punctuation">(</span>suffic<span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> s<span class="token punctuation">[</span><span class="token function">len</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token operator">-</span><span class="token function">len</span><span class="token punctuation">(</span>suffic<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token operator">==</span>suffic
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>包含子串测试：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">Contains</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span>substr <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token builtin">bool</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> i<span class="token operator">:=</span><span class="token number">0</span><span class="token punctuation">;</span>i<span class="token operator">&lt;</span><span class="token function">len</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token function">HasPrefix</span><span class="token punctuation">(</span>s<span class="token punctuation">[</span>i<span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">,</span>substr<span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token boolean">true</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token boolean">false</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>Go语言的range循环在处理字符串的时候，会自动隐式解码UTF8字符串。</p>
<p>如果遇到一个错误的UTF8编码输入，将会生成一个特殊的Unicode字符<code>\uFFFD</code>，即�。</p>
<p>UTF8作为交换格式方便，rune序列支持数组索引且方便切割，rune的大小一致。rune序列的长度就是字符的数量，string类型的数量是字符占用的字节空间大小。</p>
<p>将string转换为rune序列：<code>rune序列名:=[]rune(string类型变量名)</code>。</p>
<p>构建字符串推荐使用<code>bytes.Buffer</code>。</p>
<p>[]byte()是一个字节数组，用于保存或者操作字符串数据。</p>
<p>bytes包提供了Buffer类型用于字节slice的缓存。一个Buffer开始是空的，但随着string、byte或[]byte等类型数据的写入可以动态增长。一个bytes.Buffer变量并不需要初始化，零值也是有效的。</p>
<p>数组转换成字符串数组：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
 <span class="token string">"bytes"</span>
 <span class="token string">"fmt"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">intsToString</span><span class="token punctuation">(</span>values <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">)</span><span class="token builtin">string</span><span class="token punctuation">{</span>
	<span class="token keyword">var</span> buf bytes<span class="token punctuation">.</span>Buffer
	buf<span class="token punctuation">.</span><span class="token function">WriteByte</span><span class="token punctuation">(</span><span class="token char">'['</span><span class="token punctuation">)</span>
	<span class="token keyword">for</span> i<span class="token punctuation">,</span>v<span class="token operator">:=</span><span class="token keyword">range</span> values<span class="token punctuation">{</span>
		<span class="token keyword">if</span> i<span class="token operator">&gt;</span><span class="token number">0</span><span class="token punctuation">{</span>
			buf<span class="token punctuation">.</span><span class="token function">WriteByte</span><span class="token punctuation">(</span><span class="token char">','</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
		fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>buf<span class="token punctuation">,</span><span class="token string">"%d"</span><span class="token punctuation">,</span>v<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	buf<span class="token punctuation">.</span><span class="token function">WriteByte</span><span class="token punctuation">(</span><span class="token char">']'</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> buf<span class="token punctuation">.</span><span class="token function">String</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token function">intsToString</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>向bytes.Buffer添加任意字符的UTF8编码时，最好使用bytes.Buffer的WriteRune方法，如果仅仅是写入ASCII字符则可以使用WriteByte方法。</p>
<p>默认值是空字符串</p>
<p>string是数据类型，不是引用或指针类型</p>
<p>string是只读的byte slice ，len函数返回string对应的byte数</p>
<p>string的byte数组可以存放任意数据</p>
<p>string类型的大小都是16字节，原因是其底层结构为<code>runtime/string.go</code>中的<code>stringStruct</code>结构体，其中包含了一个指针，和一个int变量表示长度。</p>
<p>想看string内部的可以用反射变成反射的对应类型：<code>(*reflect.StringHeader)(unsafe.Pointer(&amp;s))</code></p>
<p>字符串切片：<code>s=string([]rune(s)[:3])</code></p>
<h3 id="常量">常量<a class="anchor" href="#常量">¶</a></h3>
<p>常量表达式的值在编译期计算。每种常量的潜在类型都是基础类型。</p>
<p>形式是：<code>const</code></p>
<p>可以一次性声明多个常量。语法类似import。</p>
<p>批量声明常量，除了第一个以外，可以省略常量右边的初始化表达式，其值直接和上一个赋值的结果相同。</p>
<p>常量声明可以使用iota常量生成器初始化，用以生成一组以相似规则初始化的常量。在一个const声明语句中，在第一个声明的常量所在行iota会被置为0，然后在每一个有常量声明的行加一。类似其他语言的枚举类型。如果有想跳过一个数字，可以写一个<code>-</code>。也可写带有<code>iota</code>的表达式，之后的变量都会按照该表达式进行运算。</p>
<h4 id="无类型常量">无类型常量<a class="anchor" href="#无类型常量">¶</a></h4>
<p>无类型常量可以作为任意数据类型，可以简单理解为字符替换。</p>
<p>Go语言中有着无类型常量，编译器为这些没有明确的基础类型的数字常量提供比基础类型更高精度的算数运算，可以认为至少有256bit的运算精度。</p>
<p style="filter: opacity(95%);transform:scale(0.85);text-align:center;"><img src="https://math.now.sh?from=%E6%97%A0%E7%B1%BB%E5%9E%8B%E5%B8%B8%E9%87%8F%5Cbegin%7Bcases%7D%E6%97%A0%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%B8%83%E5%B0%94%E5%9E%8B%5C%5C%E6%97%A0%E7%B1%BB%E5%9E%8B%E7%9A%84%E6%95%B4%E6%95%B0%5C%5C%E6%97%A0%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%AD%97%E7%AC%A6%5C%5C%E6%97%A0%E7%B1%BB%E5%9E%8B%E7%9A%84%E6%B5%AE%E7%82%B9%E6%95%B0%5C%5C%E6%97%A0%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%A4%8D%E6%95%B0%5C%5C%E6%97%A0%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%5Cend%7Bcases%7D%0A"></p><p>通过延迟明确常量的具体类型，不仅可以提供更高的运算精度，还可以直接用于更多的表达式而不需要显示的类型转换。</p>
<p>无类型整数常量转换为int，内存大小不确定。但是无类型浮点数内存大小明确是float64，无类型复数内存大小为complex128。</p>
<p>当尝试将无类型的常量转为一个接口值时，要依靠它们明确接口对应的动态类型。</p>
<h3 id="类型申明语句">类型申明语句<a class="anchor" href="#类型申明语句">¶</a></h3>
<p>语法：<code>type 类型名字 底层类型</code></p>
<p>一个类型声明语句创建了一个新的类型名称，和现有类型具有相同的底层结构。新命名的类型提供了一个方法，用来分隔不同概念的类型，这样即使它们底层类型相同也是不兼容的。</p>
<p>类型声明语句一般出现在包一级，因此如果新创建的类型名字的首字符大写，则在包外部也可以使用。</p>
<p>自己创建的类型string方法可以如下申明方式：<code>func (c 类型名字) String() string { return 返回信息字段 }</code></p>
<h2 id="复合数据类型">复合数据类型<a class="anchor" href="#复合数据类型">¶</a></h2>
<p>数组是由同构的元素组成。结构体是由异构元素构成。都有着固定内存大小的数据结构。slice和map是动态数据结构，能根据需要进行增长。</p>
<h3 id="数组">数组<a class="anchor" href="#数组">¶</a></h3>
<p>int类型的数组声明：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> a <span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token builtin">int</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>默认情况下，数组的每个元素都被初始化为元素类型对应的零值。</p>
<p>可以用索引位置和值来初始化数组<code>var a [3]int =[3]int {1:2}</code>，此时a有三个元素，a[1]为2,其他为0。</p>
<p>当数组的长度位置是<code>...</code>时，表明数组的长度是依据初始值的个数来计算的。例如<code>q:=[...]int{1,2,3}</code>。</p>
<p><strong>数组的长度是数组类型的一部分，不同长度的数组是不同的数组类型。</strong></p>
<p>可以指定数组中参数的初始化：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">r <span class="token operator">:=</span> <span class="token punctuation">[</span><span class="token operator">...</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">{</span><span class="token number">99</span><span class="token punctuation">:</span> <span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">}</span> <span class="token comment">//定义了一个包含100个元素的r数组，并将第100位元素初始化位-1，其他元素均为0</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>参数传递数组时，go传递的是数组的复本。当数组较大时，效率低下且无法修改到数组上。此时可以传入指针。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">zreo</span><span class="token punctuation">(</span>ptr <span class="token operator">*</span><span class="token punctuation">[</span><span class="token number">32</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token comment">//下面的代码可以简化为*ptr=[32]byte{}</span>
    <span class="token keyword">for</span> i<span class="token operator">:=</span><span class="token keyword">range</span> ptr<span class="token punctuation">{</span>
        ptr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token operator">=</span><span class="token number">0</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="Slice">Slice<a class="anchor" href="#Slice">¶</a></h3>
<p><img src="https://math.now.sh?inline=slice%5Cbegin%7Bcases%7D%E6%8C%87%E9%92%88%3A%E6%8C%87%E5%90%91%E7%AC%AC%E4%B8%80%E4%B8%AAslice%E5%85%83%E7%B4%A0%E5%AF%B9%E5%BA%94%E7%9A%84%E5%BA%95%E5%B1%82%E6%95%B0%E7%BB%84%E5%85%83%E7%B4%A0%E7%9A%84%E5%9C%B0%E5%9D%80%EF%BC%8Cslice%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%85%83%E7%B4%A0%E4%B8%8D%E4%B8%80%E5%AE%9A%E6%98%AF%E6%95%B0%E7%BB%84%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%85%83%E7%B4%A0%5C%5C%E9%95%BF%E5%BA%A6%3Aslice%E4%B8%AD%E7%9A%84%E5%85%83%E7%B4%A0%E6%95%B0%E7%9B%AE%EF%BC%8C%E5%8F%AF%E4%BB%A5%E7%94%A8len%E5%87%BD%E6%95%B0%E8%8E%B7%E5%8F%96%5C%5C%E5%AE%B9%E9%87%8F%3A%E4%BB%8Eslice%E5%BC%80%E5%A7%8B%E4%BD%8D%E7%BD%AE%E5%88%B0%E5%BA%95%E5%B1%82%E6%95%B0%E6%8D%AE%E7%9A%84%E7%BB%93%E5%B0%BE%E4%BD%8D%E7%BD%AE%EF%BC%8C%E5%8F%AF%E4%BB%A5%E7%94%A8cap%E5%87%BD%E6%95%B0%E8%8E%B7%E5%8F%96%5Cend%7Bcases%7D" style="filter: opacity(95%);transform:scale(0.85);text-align:center;display:inline-block;margin: 0;"></p>
<p>多个slice可以共享底层数据，引用的数组部分区间可能重叠。</p>
<p>slice的追加</p>
<p>扩容是，编译时转为调用<code>runtime.growslice()</code></p>
<ul>
<li>如果期望容量大于当前容量的两倍就会使用期望容量</li>
<li>如果当前切片的长度小于1024，容量翻倍</li>
<li>如果当前切片的长度大于1024，每次增加25%</li>
<li>切片扩容时，<strong>并发不安全</strong>，切片并发需要加锁</li>
</ul>
<p>slice支持切片<code>s[i:j]</code>，<img src="https://math.now.sh?inline=0%5Cleq%20i%5Cleq%20j%20%5Cleq%20cap%28s%29" style="filter: opacity(95%);transform:scale(0.85);text-align:center;display:inline-block;margin: 0;">，引用s的从第i个元素开始到第j-1个元素的子序列。i省略的话，默认为0。j省略为len(s)代替。</p>
<p>切片操作超过cap(s)的上限导致panic异常，超过len(s)表示拓展了slice</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">//翻转数组</span>
<span class="token keyword">func</span> <span class="token function">reverse</span><span class="token punctuation">(</span>s <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">int</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token keyword">for</span> i<span class="token punctuation">,</span>j<span class="token operator">:=</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token function">len</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">;</span>i<span class="token operator">&lt;</span>j<span class="token punctuation">;</span>i<span class="token punctuation">,</span>j<span class="token operator">=</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">,</span>j<span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">{</span>
        s<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">,</span>s<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token operator">=</span>s<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">,</span>s<span class="token punctuation">[</span>i<span class="token punctuation">]</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>一种将slice元素循环向左旋转n个元素的方法是三次调用reverse反转函数， 第一次是反转开头的n个元素， 然后是反转剩下的元素， 最后是反转整个slice的元素。 （ 如果是向右循环旋转，则将第三个函数调用移到第一个调用位置就可以了。 ）</p>
<p>数组能比较，slice不能比较。slice和数组在申明上的区别在于没有指明数组长度。</p>
<p>标准库提供了高度优化的bytes.Equal函数来判断两个字节型slice是否相等（ []byte）</p>
<p>slice唯一合法的比较是与nil进行比较。一个零值slice为nil，其没有底层数组，长度和容量为0。但是也有非nil值的slice长度和容量为0.</p>
<p>可以使用<code>[]int(nil)</code>类型转换表达式生成一个对应类型slice的nil值。</p>
<p>检查slice是否为空<code>len(s)==0</code>而不是<code>s==nil</code>。</p>
<p>所有go函数应该以相同的方式对待nil值的slice和0长度的slice。</p>
<p><code>make</code>函数创建一个指定元素类型、长度和容量的slice。容量可以省略，默认等于长度。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span>T<span class="token punctuation">,</span><span class="token builtin">len</span><span class="token punctuation">)</span>
<span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span>T<span class="token punctuation">,</span><span class="token builtin">len</span><span class="token punctuation">,</span><span class="token builtin">cap</span><span class="token punctuation">)</span><span class="token comment">//same as make([]T,cap)[:len]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p><code>append(slice名，需要添加的值)</code>向slice中添加元素。添加元素时如果超越cap，系统会重新分配更大的底层数组。</p>
<p>由于值传递的关系，必须接收append的返回值。</p>
<p><code>copy(slice名，拷贝源)</code></p>
<p>删除slice中的元素可以使用如下语法<code>s2=append(s2[:3],s2[4:]...)</code>。<code>...</code>表示这里是可变长度，不能省去。</p>
<h3 id="Map">Map<a class="anchor" href="#Map">¶</a></h3>
<p><code>map</code>的声明如下:<code>map[K]V</code>，复合<code>map</code>如：<code>map[K1]map[K2]V</code>。如：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">m<span class="token operator">:=</span><span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span><span class="token builtin">string</span> <span class="token punctuation">{</span>
    <span class="token string">"hello"</span><span class="token punctuation">:</span><span class="token string">"world"</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p><code>map</code>是无序的。</p>
<p>最好不要用浮点数作为key，最坏情况会出现NaN和任何浮点数不相等的情况。</p>
<p><code>map</code>中的value不可以通过取地址获取，以避免因为map扩容导致的地址迁移。</p>
<p><code>map</code>中数据的返回是无序的，如果需要按照某种顺序输出，只能在外层将key进行排序后进行输出。</p>
<p><strong><code>map</code>中没有的key对应的value是value类型的初始值。相应取值返回的第二个参数是false，如果有返回true。</strong></p>
<p><code>delete(map名，key值)</code>删除元素。</p>
<p><code>map</code>使用哈希表，key必须可以比较。除了<code>slice,map,function的内建类型</code>都可以作为key。<code>stuct</code>不包含上述字段也可作为key。</p>
<p>Go中没有set类型，但是可以通过<code>map[type]bool</code>的方式模拟set。</p>
<p>其底层是<code>runtime.hmap</code></p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E5%AD%A6%E4%B9%A0/Go%E4%B8%ADMap.png" alt="Go中Map.png"></p>
<h4 id="map使用make创建">map使用make创建<a class="anchor" href="#map使用make创建">¶</a></h4>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E5%AD%A6%E4%B9%A0/map%E4%BD%BF%E7%94%A8make%E5%88%9D%E5%A7%8B%E5%8C%96.png" alt="map使用make初始化.png"></p>
<h4 id="map使用字面量创建">map使用字面量创建<a class="anchor" href="#map使用字面量创建">¶</a></h4>
<ul>
<li>当元素少于25个时，直接转化为简单赋值，本身还是调用的make创建</li>
<li>当元素多于25个时，转化为循环赋值，本身还是调用的make创建</li>
</ul>
<h4 id="map扩容">map扩容<a class="anchor" href="#map扩容">¶</a></h4>
<p>当map溢出桶太多时会导致变成链表，进而严重的性能下降。</p>
<h4 id="总结">总结<a class="anchor" href="#总结">¶</a></h4>
<ul>
<li>go使用拉链实现了hashmap</li>
<li>每个桶中存储键哈希的前8位</li>
<li>桶超过8位，存储在溢出桶中</li>
</ul>
<h3 id="结构体">结构体<a class="anchor" href="#结构体">¶</a></h3>
<p>go的结构体没有构造函数，一般可以直接生成。如果一定要用函数进行构造，可以自己定义一个工厂函数，返回一个局部地址，但是不会出错。</p>
<p>针对函数体的函数形式如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>node <span class="token operator">*</span>TreeNode<span class="token punctuation">)</span> <span class="token function">setValue</span><span class="token punctuation">(</span>value <span class="token builtin">int</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>**go中的函数传递都是值传递，所以想对结构体中的数据进行写操作数时，需要传入的指针，而不能是值。**只有使用指针才可以改变结构内容。</p>
<p>当改变内容必须使用指针接收者，结构过大也考虑指针接收者，如果有指针接收者，最好都是指针接收者，保持一致性。</p>
<h3 id="JSON">JSON<a class="anchor" href="#JSON">¶</a></h3>
<h3 id="文本和HTML模板">文本和HTML模板<a class="anchor" href="#文本和HTML模板">¶</a></h3>
<h2 id="函数">函数<a class="anchor" href="#函数">¶</a></h2>
<p>go的函数可以返回两个值。返回值可以命名，这样可以直接写一个<code>return</code>就行，不用再写返回变量名，但是可读性差。短函数可以用。</p>
<p>函数可以作为参数传入函数。func 函数名_1(函数名_2 func(参数，参数)类型)</p>
<h2 id="方法">方法<a class="anchor" href="#方法">¶</a></h2>
<h2 id="接口">接口<a class="anchor" href="#接口">¶</a></h2>
<p>使用者来定义接口。</p>
<p>多态的使用只能是传入参数的指针或者说是引用，不能直接传入对象。</p>
<p>空接口可以表示任何类型。</p>
<p>通过断言来将空接口转换为指定类型</p>
<h3 id="最佳实践">最佳实践<a class="anchor" href="#最佳实践">¶</a></h3>
<ul>
<li>倾向于使用小的接口定义，很多接口只包含一个方法</li>
<li>较大的接口定义，可以由多个小接口定义组合而成</li>
<li>只依赖于必要功能的最小接口</li>
</ul>
<h2 id="包和工具">包和工具<a class="anchor" href="#包和工具">¶</a></h2>
<p><code>go list | wc -l</code>查看标准包的具体数目。</p>
<p>Go语言的开源程序包可以在http://godoc.org检索。</p>
<p>名字一般使用CamelCase。</p>
<p>首字母大写表示<code>public</code>，首字母小写表示<code>private</code>。</p>
<p>每个目录一个包，main包包含可执行入口。</p>
<p>为结构定义的方法必须放在同一个包内。可以是不同的文件。</p>
<p>包就是一个目录，一个目录就是一个包，包名可以不和目录名相同，但是一个目录下只能有一个包。</p>
<p>go扩充系统类型或他人的类型使用两种方法：<strong>定义别名或使用组合</strong></p>
<p>使用组合就是创建一个新的结构体，其中包含需要拓展的结构体指针作为数据成员。将结构体中的数据提取出来，创建为一个新的结构体，并对其进行操作。</p>
<p>有些go的第三方包因为国内网络环境的原因影响，可以使用第三方工具进行下载，而不是使用<code>go get</code>。方式如下：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">go get <span class="token parameter variable">-v</span> github.com/gpmgo/gopm
gopm get <span class="token parameter variable">-u</span> <span class="token parameter variable">-g</span> <span class="token parameter variable">-v</span> 包的地址
go <span class="token function">install</span> 包地址<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>在<code>go.mod</code>中使用本地文件替代包地址，可以使用在<code>go.mod</code>中追加写<code>replace github.com/XXX/ =&gt; xxx/xxx</code></p>
<p><code>go vender</code>缓存到本地</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">go mod vendor <span class="token comment">#这是go mod的vendor，不是以前的vendor</span>
go build <span class="token parameter variable">-mod</span> vendor<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>创建<code>go.mod</code>：<code>go mod init 你的仓库地址/仓库名</code></p>
<h2 id="TCP">TCP<a class="anchor" href="#TCP">¶</a></h2>
<h4 id="Socket">Socket<a class="anchor" href="#Socket">¶</a></h4>
<ul>
<li>很多系统提供Socket作为TCP网络连接的抽象</li>
<li>Linux-&gt;Internet domain socket-&gt;SOCK_STREAM</li>
<li>Linux中Socket以“文件描述符”FD作为标识</li>
</ul>
<pre class="mermaid">sequenceDiagram
participant Server
participant Client
opt 建立连接
Server -&gt;&gt; Server: socket()
Server -&gt;&gt; Server: bind()
Server -&gt;&gt; Server: listen()
Client -&gt;&gt; Client: socket()
Client -&gt;&gt; + Server: connect()
Server -&gt;&gt; - Client: accept()
end
opt 通信
Server -&gt;&gt; Server: 切换socket
Server -&gt;&gt; + Client: write()
Client -&gt;&gt; - Client: read()
Client -&gt;&gt; Server: write()
Server -&gt;&gt; Server: read()
end
opt 关闭连接
Server -&gt;&gt; Server: 切换socket
Server -&gt;&gt; + Client: close()
Client -&gt;&gt; Client:read()
Client -&gt;&gt; - Server:close()
end</pre>
<p>在上述过程中，Server端会保留一个socket作为listen使用，在此基础上，有多少个Client就会有多少个socket。因此需要选择合适的IO模型同时操作socket。</p>
<h4 id="IO模型">IO模型<a class="anchor" href="#IO模型">¶</a></h4>
<h5 id="阻塞">阻塞<a class="anchor" href="#阻塞">¶</a></h5>
<ul>
<li>同步写入Socket，线程陷入内核态</li>
<li>当读写成功后，切换回用户态，继续执行</li>
<li>优点：开发难度小，代码简单</li>
<li>缺点：内核态切换开销大</li>
</ul>
<h5 id="非阻塞">非阻塞<a class="anchor" href="#非阻塞">¶</a></h5>
<ul>
<li>如果暂时无法收发数据，会返回错误</li>
<li>应用会不断轮询，直到Socket可以读写</li>
<li>优点：不会陷入内核态，自由度高</li>
<li>缺点：需要自旋轮询</li>
</ul>
<h5 id="多路复用-Linux-epoll">多路复用-Linux epoll<a class="anchor" href="#多路复用-Linux-epoll">¶</a></h5>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E5%AD%A6%E4%B9%A0/epoll%E6%A8%A1%E5%9E%8B.png" alt="epoll模型.png"></p>
<ul>
<li>注册多个Socket事件</li>
<li>调用epoll，当有事件发生返回</li>
<li>优点：提供了事件列表，不需要查询各个Socket</li>
<li>缺点：开发难度大，逻辑复杂</li>
<li>Mac：kqueue；Windows：IOCP</li>
<li>新建多路复用器：<code>epoll_create()</code></li>
<li>往多路复用器里插入监听事件<code>epoll_ctl()</code></li>
<li>查询发生事件<code>epoll_wait()</code></li>
</ul>
<h3 id="Go的实现">Go的实现<a class="anchor" href="#Go的实现">¶</a></h3>
<ul>
<li>在底层使用OS的多路复用IO</li>
<li>在协程层面使用阻塞模型</li>
<li>阻塞协程时，休眠协程</li>
</ul>
<h4 id="epoll抽象层">epoll抽象层<a class="anchor" href="#epoll抽象层">¶</a></h4>
<p>为了统一各个OS对多路复用的实现，GO实现了Go Network Poller。</p>
<ul>
<li><code>epoll_create()-&gt;netpollinit()</code> 新建多路复用器抽象
<ul>
<li>新建epoll</li>
<li>新建一个pipe管道用于中断epoll</li>
<li>将“管道有数据到达”事件注册在epoll中</li>
</ul>
</li>
<li><code>epoll_ctl()-&gt;netpollopen()</code> 插入监听事件抽象
<ul>
<li>传入一个socket的FD和pollDesc指针</li>
<li>pollDesc指针是socket相关详细信息</li>
<li>pollDesc中记录了哪个协程休眠在等待此socket</li>
<li>将socket可读、可写、断开事件注册到epoll中</li>
</ul>
</li>
<li><code>epoll_wait()-&gt;netpoll()</code> 查询事件抽象，返回等待事件的协程列表
<ul>
<li>调用<code>epoll_wait()</code>查询有哪些事件发生</li>
<li>根据socket相关的pollDesc信息，返回哪些协程可以唤醒</li>
</ul>
</li>
</ul>
<h2 id="HTTP">HTTP<a class="anchor" href="#HTTP">¶</a></h2>
<h3 id="路由规则">路由规则<a class="anchor" href="#路由规则">¶</a></h3>
<ul>
<li>URL分为两种：
<ul>
<li>末尾是<code>/</code>：表示一个子树。后面可以跟其他子路径</li>
<li>末尾不是<code>/</code>：表示一个叶子。固定的路径</li>
</ul>
</li>
<li>采用最长匹配原则，如果有多个匹配，一定采用匹配路径最长的那个进行处理</li>
<li>如果没有找到任何匹配项，会返回404错误</li>
</ul>
<h2 id="锁">锁<a class="anchor" href="#锁">¶</a></h2>
<h3 id="Atomic">Atomic<a class="anchor" href="#Atomic">¶</a></h3>
<ul>
<li><strong>Atomic机制需要在硬件级别加锁</strong></li>
<li>需要CPU硬件支持</li>
<li>不同平台的实现方案不同</li>
<li>保证操作一个变量的时候，其他协程/线程无法访问</li>
<li><strong>只能用于简单变量的简单操作</strong></li>
</ul>
<h3 id="sema锁">sema锁<a class="anchor" href="#sema锁">¶</a></h3>
<ul>
<li>信号量锁/信号锁</li>
<li>核心是一个uint32值，含义是同时可并发的数量</li>
<li>每个sema锁都对应一个SemaRoot结构体</li>
<li>SameRoot中有一个平衡二叉树用于协程排队</li>
</ul>
<h4 id="sema操作">sema操作<a class="anchor" href="#sema操作">¶</a></h4>
<ul>
<li>
<p>uint32&gt;0</p>
<ul>
<li>
<p>获取锁：uint32减一，获取成功</p>
</li>
<li>
<p>释放锁：uint32加一，释放成功</p>
</li>
</ul>
</li>
<li>
<p>uint32==0</p>
<ul>
<li>获取锁：协程休眠，进入堆树等待</li>
<li>释放锁：从堆树中取出一个协程，唤醒</li>
<li>sema锁退化成一个专用休眠队列</li>
</ul>
</li>
</ul>
<p>sema可以直接配置成0，作为休眠队列。</p>
<h3 id="Mutex">Mutex<a class="anchor" href="#Mutex">¶</a></h3>
<p><code>sync.Mutex</code>：<code>Lock()</code>与<code>Unlock()</code></p>
<p>使用互斥锁能够保证同一时间有且只有一个goroutine进入临界区，其他的goroutine则在等待锁；当互斥锁释放后，等待的goroutine才可以获取锁进入临界区，多个goroutine同时等待一个锁时，唤醒的策略是随机的。但是，这种方式还是有问题的，读写都会等待，大大降低了程序效率。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 多个goroutine并发操作全局变量x</span>
<span class="token keyword">var</span> x <span class="token builtin">int64</span>
<span class="token keyword">var</span> wg sync<span class="token punctuation">.</span>WaitGroup
<span class="token keyword">var</span> lock sync<span class="token punctuation">.</span>Mutex <span class="token comment">// 互斥锁</span>

<span class="token keyword">func</span> <span class="token function">add</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token punctuation">{</span>
    <span class="token keyword">for</span> i <span class="token operator">:=</span><span class="token number">0</span><span class="token punctuation">;</span>i<span class="token operator">&lt;</span><span class="token number">1000</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">{</span>
        lock<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>     <span class="token comment">// 加锁</span>
        x <span class="token operator">=</span> x <span class="token operator">+</span> <span class="token number">1</span>
        lock<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>   <span class="token comment">// 解锁</span>
    <span class="token punctuation">}</span>
    wg<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token punctuation">{</span>
    wg<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
    <span class="token keyword">go</span> <span class="token function">add</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">go</span> <span class="token function">add</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    wg<span class="token punctuation">.</span><span class="token function">Wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>锁竞争严重时，互斥锁进入饥饿模式，也就是协程需要等待1ms。</p>
<pre class="mermaid">graph LR
Mutex--&gt;state
Mutex--&gt;sema--&gt;SemaRoot
SemaRoot--&gt;treap
SemaRoot--&gt;nwait
treap--&gt;sudog
treap--&gt;g
state--&gt;最低第一位:Locked--&gt;1:已锁
最低第一位:Locked---&gt;0:未锁
state--&gt;最低第二位:Woken--&gt;睡眠中唤醒
state--&gt;最低第三位:Starving--&gt;饥饿模式
state--&gt;其余位数:WaiterShift--&gt;等待锁数量</pre>
<h4 id="正常模式">正常模式<a class="anchor" href="#正常模式">¶</a></h4>
<ul>
<li>加锁
<ul>
<li>
<p>尝试CAS直接加锁</p>
</li>
<li>
<p>若无法直接获取，进行多次自旋尝试</p>
</li>
<li>
<p>多次尝试失败，进入sema队列休眠</p>
</li>
<li>
<p>可能导致锁饥饿</p>
</li>
</ul>
</li>
</ul>
<h4 id="饥饿模式">饥饿模式<a class="anchor" href="#饥饿模式">¶</a></h4>
<ul>
<li>当前协程等待锁的时间超过了1ms，切换到饥饿模式，表示位设置为1</li>
<li>饥饿模式中，不自旋，新来的协程直接sema休眠</li>
<li>饥饿模式中，被唤醒的协程直接获取锁</li>
<li>没有协程在队列中继续等待时，回到正常模式</li>
<li>饥饿模式没有自旋等待，有利于公平</li>
</ul>
<h3 id="读写互斥锁">读写互斥锁<a class="anchor" href="#读写互斥锁">¶</a></h3>
<ul>
<li>只读时，不能修改</li>
<li>只读时，多协程共享读</li>
<li>只读时，不需要互斥锁</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> RWMutex <span class="token keyword">struct</span><span class="token punctuation">{</span>
    w Mutex <span class="token comment">// 互斥锁作为写锁</span>
    writerSem <span class="token builtin">uint32</span> <span class="token comment">// 作为写协程队列</span>
    readerSem <span class="token builtin">uint32</span> <span class="token comment">// 作为读协程队列</span>
    readerCount <span class="token builtin">int32</span> <span class="token comment">// 正值：正在读的协程 负值：加了写锁</span>
    readerWait <span class="token builtin">int32</span> <span class="token comment">// 写锁应该等待读协程个数</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="加写锁">加写锁<a class="anchor" href="#加写锁">¶</a></h4>
<ol>
<li>先加mutex写锁，若已经被加写锁会阻塞等待</li>
<li>将readerCount变成负值，阻塞读锁的获取</li>
<li>计算需要等待多少个读协程释放</li>
<li>如果需要等待读协程释放，陷入writerSem</li>
</ol>
<h4 id="解写锁">解写锁<a class="anchor" href="#解写锁">¶</a></h4>
<ol>
<li>将readerCount变为正值，允许读锁的获取</li>
<li>释放在readerSem中等待的读协程</li>
<li>解锁mutex</li>
</ol>
<h4 id="加读锁">加读锁<a class="anchor" href="#加读锁">¶</a></h4>
<ol>
<li>将readCount加一</li>
<li>如果readCount是正数，加锁成功</li>
<li>如果readCount是负数，说明被加了写锁，陷入readerSem</li>
</ol>
<h4 id="解写锁-2">解写锁<a class="anchor" href="#解写锁-2">¶</a></h4>
<ol>
<li>给readerCount减一</li>
<li>如果readerCount是正数，解锁成功</li>
<li>如果readerCount是负数，有写锁在排队
<ol>
<li>如果是readerWait的最后一个，唤醒写协程</li>
</ol>
</li>
</ol>
<p>在大多数场景下，是读多写少的，，当我们并发的去读取一个资源不涉及资源修改的时候是没有必要加锁的。这种情况就可以使用读写互斥锁，Go语言中使用sync包中的RWMutex类型。读写锁分为两种：读锁和写锁。当一个goroutine获取读锁之后，其他的goroutine如果是获取读锁会继续获得锁，如果是获取写锁就会等待；当一个goroutine获取写锁之后，其他的goroutine无论是获取读锁还是写锁都会等待。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 读写互斥锁</span>
<span class="token keyword">var</span> <span class="token punctuation">(</span>
    x <span class="token builtin">int64</span>
    lock sync<span class="token punctuation">.</span>RWMutex
    wg  sync<span class="token punctuation">.</span>WaitGroup
<span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token function">read</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token punctuation">{</span>
    lock<span class="token punctuation">.</span><span class="token function">RLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>        <span class="token comment">// 读加锁</span>
    time<span class="token punctuation">.</span><span class="token function">Sleep</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span>Millisecond<span class="token punctuation">)</span>        <span class="token comment">// 读操作耗时1ms</span>
    lock<span class="token punctuation">.</span><span class="token function">RUnlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token comment">//解锁</span>
    wg<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">write</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token punctuation">{</span>
    lock<span class="token punctuation">.</span><span class="token function">RLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>        <span class="token comment">// 写加锁</span>
    x <span class="token operator">+=</span> <span class="token number">1</span>
    time<span class="token punctuation">.</span><span class="token function">Sleep</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span>Millisecond <span class="token operator">*</span><span class="token number">2</span><span class="token punctuation">)</span> <span class="token comment">// 写操作耗时2ms</span>
    lock<span class="token punctuation">.</span><span class="token function">RUnlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    wg<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="wait-Group">wait.Group<a class="anchor" href="#wait-Group">¶</a></h3>
<p>一个waitGroup对象可以等待一组协程结束。</p>
<pre class="mermaid">graph LR
wait.Group--&gt;state1--&gt;waiter--&gt;有多少个协程在等待运行
state1--&gt;counter--&gt;有多少个协程正在运行
state1--&gt;sema--&gt;记录正在等待的协程
wait.Group--&gt;noCopy--&gt;nocopy[编译期go vet工具会检查nocopy,避免被拷贝]</pre>
<h4 id="Wait">Wait<a class="anchor" href="#Wait">¶</a></h4>
<ul>
<li>如果waiter和counter都为0，直接返回</li>
<li>否则，waiter+=1，陷入sema</li>
</ul>
<h4 id="Done">Done<a class="anchor" href="#Done">¶</a></h4>
<ul>
<li>count-=1</li>
<li>add(-1)</li>
</ul>
<h4 id="Add">Add<a class="anchor" href="#Add">¶</a></h4>
<ul>
<li>Add counter</li>
<li>if counter =0 &amp;&amp; waiter=0： return</li>
<li>counter=0 &amp;&amp; waiter!=0=&gt;唤醒sema中的所有协程</li>
</ul>
<h3 id="使用经验">使用经验<a class="anchor" href="#使用经验">¶</a></h3>
<ul>
<li>
<p>减少锁的使用时间，只在关键地方加锁</p>
</li>
<li>
<p>善用defer确保锁释放</p>
</li>
<li>
<p>读多写少用读写锁</p>
</li>
<li>
<p>永远不要拷贝锁，锁拷贝可能导致死锁的问题。因为如果拷贝的是一个已经Lock的锁，那么拷贝出的锁也是一个Lock的锁。不会因为被拷贝锁的UnLock而UnLock。而且拷贝出来的sema二叉树也不知道什么样。当结构体中有锁作为成员时，可以用<code>go vet</code>发现。</p>
</li>
<li>
<p>RACE竞争检测</p>
<ul>
<li>发现隐含的数据竞争问题</li>
<li>可能是加锁的建议</li>
<li>可能是bug的提醒</li>
<li><code>go build -race </code>执行编译出的二进制文件可以看到</li>
</ul>
</li>
<li>
<p>go-deadlock检测</p>
<ul>
<li>下载这个mod</li>
<li>检测可能的死锁</li>
<li>实际是检测获取锁的等待时间</li>
</ul>
</li>
</ul>
<h2 id="Goroutines">Goroutines<a class="anchor" href="#Goroutines">¶</a></h2>
<p><strong>注意循环内多协程引用循环变量问题</strong></p>
<p><code>goroutine</code>是一种函数的并发执行方式，<code>channel</code>在<code>goroutine</code>之间进行参数传递。</p>
<p><code>main</code>函数本身运行在一个<code>goroutine</code>中。</p>
<p><code>go 函数名(参数)</code>表示创建一个新的<code>goroutine</code>，并在新的<code>goroutine</code>中运行这个函数。</p>
<p><code>make(chan 传递的参数类型)</code>表示创建一个指定类型的<code>channel</code>。</p>
<p>当一个<code>goroutine</code>尝试在一个<code>channel</code>上做<code>send</code>或者<code>receive</code>操作时，这个<code>goroutine</code>会阻塞在调用处，直至另一个<code>goroutine</code>往这个<code>channel</code>里写入或者接收值，这样两个<code>goroutine</code>才会继续执行<code>channel</code>操作之后的逻辑。</p>
<p>每一个<code>fetch</code>函数往<code>channel</code>中输入数据(ch&lt;-expression)，主函数接收<code>channel</code>中的数值(&lt;-ch)。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token operator">&lt;</span>变量名<span class="token operator">&gt;</span> <span class="token operator">&lt;</span>变量类型<span class="token operator">&gt;</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token comment">// 逻辑操作</span>
<span class="token punctuation">}</span><span class="token punctuation">(</span>传入参数<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>依赖于Go本身是通过值传递来实现，因此这样协程内使用的传参的值拷贝。但是如果协程内直接使用外部的变量，虽然协程内可以使用，但是此时的变量是所有协程共享的，需要注意。</p>
<p><strong>Go中不能直接杀死协程。</strong></p>
<h3 id="Thread-vs-Goroutine">Thread vs Goroutine<a class="anchor" href="#Thread-vs-Goroutine">¶</a></h3>
<ol>
<li>创建时默认的stack的大小
<ul>
<li>JDK5以后JAVA Thread stack默认为1M</li>
<li>Groutine的Stack初始化大小为2K</li>
</ul>
</li>
<li>和KSE（Kernel Space Entity）的对应关系
<ul>
<li>Java Thread是1:1</li>
<li>Goroutine是M:N</li>
</ul>
</li>
</ol>
<p>kernel entity由cpu进行调度，切换时会涉及内核上下文的切换。</p>
<h3 id="声明共享变量">声明共享变量<a class="anchor" href="#声明共享变量">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">var</span> mu sync<span class="token punctuation">.</span>Mutex
mu<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment">//操作</span>
mu<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">TestCounter</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">var</span> mut sync<span class="token punctuation">.</span>Mutex
	<span class="token keyword">var</span> wg sync<span class="token punctuation">.</span>WaitGroup
	counter <span class="token operator">:=</span> <span class="token number">0</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">5000</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		wg<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
		<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token keyword">defer</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
				mut<span class="token punctuation">.</span><span class="token function">Unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			mut<span class="token punctuation">.</span><span class="token function">Lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			counter<span class="token operator">++</span>
			wg<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	wg<span class="token punctuation">.</span><span class="token function">Wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	t<span class="token punctuation">.</span><span class="token function">Log</span><span class="token punctuation">(</span>counter<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="多渠道选择">多渠道选择<a class="anchor" href="#多渠道选择">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">select</span> <span class="token punctuation">{</span>
    <span class="token keyword">case</span> ret<span class="token operator">:=</span><span class="token operator">&lt;-</span>retCh1<span class="token punctuation">:</span>
    	t<span class="token punctuation">.</span><span class="token function">Logf</span><span class="token punctuation">(</span><span class="token string">"result %s"</span><span class="token punctuation">,</span>ret<span class="token punctuation">)</span>
    <span class="token keyword">case</span> ret<span class="token operator">:=</span><span class="token operator">&lt;-</span>retCh2<span class="token punctuation">:</span>
    	t<span class="token punctuation">.</span><span class="token function">Logf</span><span class="token punctuation">(</span><span class="token string">"result %s"</span><span class="token punctuation">,</span>ret<span class="token punctuation">)</span>
    <span class="token keyword">default</span><span class="token punctuation">:</span>
    t<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token string">"No one returned"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="超时控制">超时控制<a class="anchor" href="#超时控制">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">select</span> <span class="token punctuation">{</span>
    <span class="token keyword">case</span> ret<span class="token operator">:=</span><span class="token operator">&lt;-</span>retCh<span class="token punctuation">:</span>
    	t<span class="token punctuation">.</span><span class="token function">Logf</span><span class="token punctuation">(</span><span class="token string">"redult %s"</span><span class="token punctuation">,</span>ret<span class="token punctuation">)</span>
    <span class="token keyword">case</span> <span class="token operator">&lt;-</span>time<span class="token punctuation">.</span><span class="token function">After</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span>Second<span class="token operator">*</span><span class="token number">1</span><span class="token punctuation">)</span>
    	t<span class="token punctuation">.</span><span class="token function">Error</span><span class="token punctuation">(</span><span class="token string">"time out"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="channel-关闭">channel 关闭<a class="anchor" href="#channel-关闭">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token function">close</span><span class="token punctuation">(</span><span class="token operator">&lt;</span>channel<span class="token operator">&gt;</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ul>
<li>向关闭的channel 发送数据，会导致panic。</li>
<li><code>v,ok&lt;-ch;ok</code>为bool值，true表示正常接受，false表示通道关闭。</li>
<li>所有的channel接受者都会在channel关闭时，立即从阻塞线程等待中返回且上述ok值为false。这个广播机制被常利用，进行向多个订阅者同时发送信号。</li>
</ul>
<h3 id="多协程下只运行一次">多协程下只运行一次<a class="anchor" href="#多协程下只运行一次">¶</a></h3>
<p>单例模式在Go的实现：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> SingletonObj <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
<span class="token keyword">var</span> once sync<span class="token punctuation">.</span>Once
<span class="token keyword">var</span> obj <span class="token operator">*</span>SingletonObj
<span class="token keyword">func</span> <span class="token function">GetSingletonObj</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span>SingletonObj<span class="token punctuation">{</span>
	once<span class="token punctuation">.</span><span class="token function">Do</span><span class="token punctuation">(</span><span class="token keyword">func</span> <span class="token punctuation">(</span><span class="token punctuation">)</span>  <span class="token punctuation">{</span>
		fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Create Singletom obj"</span><span class="token punctuation">)</span>
		obj<span class="token operator">=</span><span class="token operator">&amp;</span>SingletonObj<span class="token punctuation">{</span><span class="token punctuation">}</span>
	<span class="token punctuation">}</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> obj
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="协程切换">协程切换<a class="anchor" href="#协程切换">¶</a></h3>
<ul>
<li>主动挂起：<code>gopark()</code></li>
<li>系统调用：<code>entresyscall()-&gt;系统调用-&gt;exitsyscall()</code></li>
<li>基于协作的抢占：业务主动调用<code>morestack()</code></li>
<li>基于信号的抢占：强制线程调用<code>doSigPreempt()</code>。通过发送GC发送SIGURG</li>
</ul>
<h3 id="协程太多的处理方案">协程太多的处理方案<a class="anchor" href="#协程太多的处理方案">¶</a></h3>
<ul>
<li>优化业务逻辑</li>
<li>利用channel的缓存区，在go协程前增加<code>a:=make(chan struct{},3000);a&lt;-struct{}{}</code>。在协程执行完成后<code>&lt;-ch</code>
<ul>
<li>启动协程前，向channle送入一个空结构体</li>
<li>协程结束，取出一个空结构体</li>
</ul>
</li>
<li>协程池
<ul>
<li>预创建一定数量的协程</li>
<li>将任务送入协程池队列</li>
<li>协程池不断取出可用协程，执行任务</li>
</ul>
</li>
<li>调整系统资源</li>
</ul>
<p>不推荐使用协程池：</p>
<ul>
<li>Go语言的线程已经相当于池化</li>
<li>二级池化会增加系统复杂度</li>
<li>Go语言的初衷是希望协程即用即毁，不要池化</li>
</ul>
<h2 id="基于共享变量的并发">基于共享变量的并发<a class="anchor" href="#基于共享变量的并发">¶</a></h2>
<h2 id="Channel">Channel<a class="anchor" href="#Channel">¶</a></h2>
<p>Channel中包含<code>hchan</code>结构：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 环形缓冲区</span>
qcount <span class="token builtin">uint</span>
dataqsiz <span class="token builtin">uint</span>
buf unsafe<span class="token punctuation">.</span>Pointer
elemsize <span class="token builtin">uint16</span>
elemtype <span class="token operator">*</span>_type
<span class="token comment">// 发送队列</span>
sendx <span class="token builtin">uint</span>
sendq waitq
<span class="token comment">// 接收队列</span>
recvx <span class="token builtin">uint</span>
recvq waitq
<span class="token comment">// 互斥锁并不是排队发送/接收数据，保护的是hchan结构体本身</span>
lock mutex
<span class="token comment">// 表明当前channel是开放还是关闭，0开启，1关闭</span>
closed <span class="token builtin">uint32</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上述元素形成了一个环形缓冲区，大幅降低了GC的开销。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> waitq <span class="token keyword">struct</span><span class="token punctuation">{</span>
    first <span class="token operator">*</span>sudog
    last <span class="token operator">*</span>sudog
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>Channel并不是无锁的，其中的hchan结构体中含有锁。</strong></p>
<p><code>&lt;-</code>关键字是一个语法糖</p>
<ul>
<li>在发送时会在编译阶段，将<code>c&lt;-</code>转化为<code>runtime.chansend1()</code>，<code>runtime.chansend1()</code>调用<code>runtime.chansend()</code></li>
<li>在接收时会在编译阶段根据是否接收发送的状态采用不同的转换
<ul>
<li><code>i&lt;-c</code>转化为<code>runtime.chanrecv1()</code></li>
<li><code>i,ok&lt;-c</code>转化为<code>runtime.chanrecv2()</code></li>
<li>但是上述两种方法最终都是调用<code>chanrecv()</code>方法</li>
</ul>
</li>
</ul>
<h3 id="直接发送">直接发送<a class="anchor" href="#直接发送">¶</a></h3>
<p>发送前，已经有G在休眠等待接受。此时缓存空，不用考虑缓存。从队列中取出一个等待接收的G。将数据直接拷贝给G的接受变量，唤醒G。</p>
<h3 id="放入缓存">放入缓存<a class="anchor" href="#放入缓存">¶</a></h3>
<p>获取可存入的缓存地址，存入数据，维护索引。</p>
<h3 id="休眠等待">休眠等待<a class="anchor" href="#休眠等待">¶</a></h3>
<p>没有G在休眠等待，而且没有缓存或满了，自己进入发送队列，休眠等待。</p>
<h3 id="有等待的G，从G接收">有等待的G，从G接收<a class="anchor" href="#有等待的G，从G接收">¶</a></h3>
<p>接收数据前，已经有G在休眠等待，而且这个Channel没有缓存。将数据直接从G拷贝过来，唤醒G。</p>
<p>实现：</p>
<ol>
<li>判断有G在发送队列等待，进入<code>recv()</code></li>
<li>判断此Channel无缓存</li>
<li>直接从等待的G中取走数据，唤醒G</li>
</ol>
<h3 id="有等待的G，从缓存接收">有等待的G，从缓存接收<a class="anchor" href="#有等待的G，从缓存接收">¶</a></h3>
<p>接收数据前，已经有G在休眠等待发送，而且这个Channel有缓存。从缓存取走一个数据。将休眠G的数据放进缓存，唤醒G。</p>
<p>实现：</p>
<ol>
<li>判断有G在发送队列等待，进入<code>recv()</code></li>
<li>判断此Channel有缓存</li>
<li>从缓存中取走一个数据</li>
<li>将G的数据放入缓存，唤醒G</li>
</ol>
<h3 id="接收缓存">接收缓存<a class="anchor" href="#接收缓存">¶</a></h3>
<p>没有G在休眠等待发送，但是缓存有内容。从缓存中取数据。</p>
<p>实现：</p>
<ol>
<li>判断没有G在发送队列等待</li>
<li>判断此Channel有缓存</li>
<li>从缓存取数据</li>
</ol>
<h3 id="阻塞缓存">阻塞缓存<a class="anchor" href="#阻塞缓存">¶</a></h3>
<p>没有G在休眠等待，而且没有缓存或缓存为空。进入接收队列，休眠等待。</p>
<p>实现：</p>
<ol>
<li>判断没有G在发送队列等待</li>
<li>判断此Channel无缓存</li>
<li>将自己包装成sudog</li>
<li>sudog放入接收等待队列，休眠</li>
<li>唤醒时，发送的G已经将数据拷贝走</li>
</ol>
<h2 id="包和工具-2">包和工具<a class="anchor" href="#包和工具-2">¶</a></h2>
<p>需要将想用的GOPATH添加对应的项目地址以保证在GOPATH拼接完成import的字符后能够导入对应的包。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">import</span> <span class="token operator">&lt;</span>包别名<span class="token operator">&gt;</span> <span class="token string">"引用路径"</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 强制获取最新的包</span>
go get <span class="token parameter variable">-u</span> <span class="token operator">&lt;</span>包名<span class="token operator">&gt;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>不要把src放在路径中，这样<code>go get</code>将获取不到。</p>
<h2 id="Context">Context<a class="anchor" href="#Context">¶</a></h2>
<ul>
<li>根Context：通过<code>context.Background()</code>创建</li>
<li>创建子节点Context：
<ul>
<li><code>func WithCancel(parent Context) (ctx Context, cancel CancelFunc)</code></li>
<li><code>func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)</code></li>
<li><code>func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)</code></li>
<li><code>func WithValue(parent Context, key, val any) Context</code></li>
</ul>
</li>
</ul>
<p>Context用于解决goroutine之间退出通知、元数据传递的功能的问题。</p>
<p>最佳实践：</p>
<ul>
<li>不要将context放在结构体中，而是直接将context类型作为函数的第一参数，而且一般都命名为ctx</li>
<li>不要向函数内传出nil属性的context，不知传什么，用TODO函数</li>
<li>不要把本应该作为函数参数的属性塞进context，context存储的应该是一些共同的数据</li>
<li>同一个context可能会被传递到多个goroutine中，但是context并发安全</li>
</ul>
<h2 id="init方法">init方法<a class="anchor" href="#init方法">¶</a></h2>
<ul>
<li>在main被执行前，所有依赖的package的init方法都会被执行</li>
<li>不同包的init函数按照包导入的依赖关系决定执行顺序</li>
<li>每个包可以有多个init函数</li>
<li>包的每个源文件也可以有多个init函数</li>
</ul>
<h2 id="vendor路径">vendor路径<a class="anchor" href="#vendor路径">¶</a></h2>
<p>随着Go1.5的发布，vendor目录被添加到出路GOPATH和GOROOT之外的依赖目录查找的解决方案。在Go 1.6之前，需要手动的设置环境变量。</p>
<p>查找依赖包路径的解决方案如下：</p>
<ol>
<li>当前包下的vendor目录</li>
<li>向上级目录查找，直到找到src下的vendor目录</li>
<li>在GOPATH下面查找依赖包</li>
<li>在GOROOT目录下查找</li>
</ol>
<h2 id="测试">测试<a class="anchor" href="#测试">¶</a></h2>
<p>源码文件以<code>_test</code>结尾：xxx_test.go</p>
<p>测试方法名以Test开头</p>
<p><code>go test -v -cover</code>：显示执行过程中的输出，并且显示代码覆盖率</p>
<h3 id="内置单元测试框架">内置单元测试框架<a class="anchor" href="#内置单元测试框架">¶</a></h3>
<ul>
<li>Fail,Error：该测试失败，该测试继续，其他测试继续执行</li>
<li>FailNow,Fatel：该测试失败，该测试终止，其他测试继续执行</li>
</ul>
<h3 id="第三方测试框架">第三方测试框架<a class="anchor" href="#第三方测试框架">¶</a></h3>
<p>https://github.com/stretchr/testify</p>
<h3 id="BenchMark">BenchMark<a class="anchor" href="#BenchMark">¶</a></h3>
<p>测试代码性能可以在<code>*_test.go</code>文件中添加如下语法：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">BenchmarkXxxx</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">//前置操作</span>
	b<span class="token punctuation">.</span><span class="token function">ResetTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 清除前置操作的时间影响</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> b<span class="token punctuation">.</span>N<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		<span class="token comment">// 性能测试代码实现</span>
	<span class="token punctuation">}</span>
	b<span class="token punctuation">.</span><span class="token function">StopTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token comment">// 结束性能测试计算</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>执行时使用命令<code>go test -bench=.</code> 这是执行所有benchMark。</p>
<p>单个benchMark可以使用<code>go -test -bench=&lt;相关benchmark测试&gt;</code>。</p>
<p>使用<code>-benchmem</code>可以获得benchmark过程中内存的情况。</p>
<h3 id="BDD">BDD<a class="anchor" href="#BDD">¶</a></h3>
<p>https://github.com/smartystreets/goconvey</p>
<h2 id="sync-Pool对象缓存">sync.Pool对象缓存<a class="anchor" href="#sync-Pool对象缓存">¶</a></h2>
<p style="filter: opacity(95%);transform:scale(0.85);text-align:center;"><img src="https://math.now.sh?from=Processor%20%5Cbegin%7Bcases%7D%20%E7%A7%81%E6%9C%89%E5%AF%B9%E8%B1%A1%20%3C-%E5%8D%8F%E7%A8%8B%E5%AE%89%E5%85%A8%20%5C%5C%20%E5%85%B1%E4%BA%AB%E6%B1%A0%20%3C-%E5%8D%8F%E7%A8%8B%E4%B8%8D%E5%AE%89%E5%85%A8%20%5Cend%7Bcases%7D%0A"></p><h3 id="对象的获取">对象的获取<a class="anchor" href="#对象的获取">¶</a></h3>
<ul>
<li>尝试从私有对象获取</li>
<li>私有对象不存在时，尝试从当前Processor的共享池获取</li>
<li>如果当前Processor共享池也是空的，那么就尝试去其他Processor的共享池获取</li>
<li>如果当前Processor共享池也是空的，那么尝试去其他Processor的共享池获取</li>
<li>如果所有子池都是空的，那么就用用户指定的New函数产生一个新的对象返回</li>
</ul>
<h3 id="对象的存放">对象的存放<a class="anchor" href="#对象的存放">¶</a></h3>
<ul>
<li>如果私有对象不存在则保存为私有对象</li>
<li>如果私有对象存在，放入当前Processor子池的共享池中</li>
</ul>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestPool</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	pool <span class="token operator">:=</span> sync<span class="token punctuation">.</span>Pool<span class="token punctuation">{</span>
		New<span class="token punctuation">:</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> any <span class="token punctuation">{</span>
			<span class="token keyword">return</span> <span class="token number">0</span>
		<span class="token punctuation">}</span><span class="token punctuation">,</span>
	<span class="token punctuation">}</span>
	pool<span class="token punctuation">.</span><span class="token function">Put</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span>
	arry <span class="token operator">:=</span> pool<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token builtin">int</span><span class="token punctuation">)</span>
	<span class="token operator">...</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="生命周期-2">生命周期<a class="anchor" href="#生命周期-2">¶</a></h3>
<ul>
<li>GC会清除sync.Pool缓存的对象，可以手动通过<code>runtime.GC()</code>进行实验</li>
<li>对象的缓存有效期为下一次GC之前</li>
</ul>
<h3 id="总结-2">总结<a class="anchor" href="#总结-2">¶</a></h3>
<ul>
<li>适用于通过复用、降低复杂对象的创建和GC代价</li>
<li>协程安全，<strong>会有锁的开销</strong></li>
<li>生命周期受GC影响，不适合做连接池等，需要自己管理生命周期的资源池化</li>
</ul>
<h2 id="反射">反射<a class="anchor" href="#反射">¶</a></h2>
<h3 id="reflect-TypeOf-vs-reflect-ValueOf">reflect.TypeOf vs. reflect.ValueOf<a class="anchor" href="#reflect-TypeOf-vs-reflect-ValueOf">¶</a></h3>
<ul>
<li><code>reflect.TypeOf</code>返回类型<code>(reflect.Type)</code></li>
<li><code>reflect.ValueOf</code>返回值<code>(reflect.Value)</code></li>
<li>可以从<code>reflect.ValueOf().Type()</code>获得类型</li>
<li>通过kind来判断类型</li>
<li><code>reflect.ValueOf(*t).FieldByName("Name")</code></li>
<li><code>reflect.ValueOf(t).MethodByName("UpdateAge").Call([]reflect.Value{reflect.ValueOf((1))})</code></li>
<li>使用<code>Elem()</code>将指针提取出其指向的结构</li>
</ul>
<h2 id="struct-tag">struct tag<a class="anchor" href="#struct-tag">¶</a></h2>
<p>代码形式如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Xxxx <span class="token keyword">struct</span><span class="token punctuation">{</span>
    Xx 
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h2 id="Unsafe">Unsafe<a class="anchor" href="#Unsafe">¶</a></h2>
<p>可以利用unsafe实现类型的强制转换。</p>
<h2 id="Pipe-Filter模式">Pipe-Filter模式<a class="anchor" href="#Pipe-Filter模式">¶</a></h2>
<ul>
<li>非常适合与数据处理及数据分析系统</li>
<li>Filter封装数据处理的能力</li>
<li>松耦合：Filter只跟数据（格式）耦合</li>
<li>Pipe用于连接FIlter传递数据或者在异步处理过程中缓冲数据流</li>
<li>进程内同步调用时，pipie演变成数据在方法调用间传递</li>
</ul>
<h2 id="Micro-Kernel">Micro Kernel<a class="anchor" href="#Micro-Kernel">¶</a></h2>
<ul>
<li>特点
<ul>
<li>易于扩展</li>
<li>错误隔离</li>
<li>保持架构一致性</li>
</ul>
</li>
<li>要点
<ul>
<li>内核包含公共流程或通用逻辑</li>
<li>将可变或可扩展部分规划为扩展点</li>
<li>抽象扩展点行为，定义接口</li>
<li>利用插件进行扩展</li>
</ul>
</li>
</ul>
<h2 id="底层编程">底层编程<a class="anchor" href="#底层编程">¶</a></h2>
<h2 id="错误处理">错误处理<a class="anchor" href="#错误处理">¶</a></h2>
<p>定义不同的错误变脸，以便于判断错误类型。</p>
<p>处理错误避免嵌套，优先处理错误，使得代码更加简洁。</p>
<h3 id="panic">panic<a class="anchor" href="#panic">¶</a></h3>
<ul>
<li>panic用于不可恢复的错误</li>
<li>panic退出前会执行defer指定的内容</li>
<li>os.Exit退出时不会调用defer指定的函数</li>
<li>os.Exit退出时不输出当前调用栈信息</li>
</ul>
<h3 id="recover">recover<a class="anchor" href="#recover">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">defer</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> err<span class="token operator">:=</span><span class="token function">recover</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>err<span class="token operator">!=</span><span class="token boolean">nil</span><span class="token punctuation">{</span>
        <span class="token comment">//恢复错误</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>使用recover需要注意，没有处理好会形成僵尸服务进程，导致health check失效。</p>
<h2 id="CSP">CSP<a class="anchor" href="#CSP">¶</a></h2>
<h3 id="CSP-vs-Actor">CSP vs Actor<a class="anchor" href="#CSP-vs-Actor">¶</a></h3>
<ul>
<li>和Actor的直接通讯不同，CSP通讯通过Channel进行通讯，松耦合。</li>
<li>Go中channel是有容量限制并且独立于处理Goroutine。Erlang的Actor模式中的mailbox容量无限，接收进程也总是被动的处理消息。</li>
</ul>
<h2 id="性能分析">性能分析<a class="anchor" href="#性能分析">¶</a></h2>
<h3 id="graphviz">graphviz<a class="anchor" href="#graphviz">¶</a></h3>
<h3 id="go-torch">go-torch<a class="anchor" href="#go-torch">¶</a></h3>
<h2 id="GC">GC<a class="anchor" href="#GC">¶</a></h2>
<p>打开GC日志</p>
<p>在程序执行之前加上环境变量<code>GODEBUG=gctrace=1</code></p>
<h3 id="go-tool-trace">go tool trace<a class="anchor" href="#go-tool-trace">¶</a></h3>
<ul>
<li>
<p>普通程序输出trace信息</p>
  <pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">import</span> <span class="token string">"runtime/trace"</span>
<span class="token keyword">func</span> <span class="token function">TestTrace</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span><span class="token punctuation">{</span>
	f<span class="token punctuation">,</span>err<span class="token operator">:=</span>os<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token string">"trace.out"</span><span class="token punctuation">)</span>
	<span class="token keyword">if</span> err<span class="token operator">!=</span><span class="token boolean">nil</span><span class="token punctuation">{</span>
		<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">defer</span> f<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	err<span class="token operator">=</span>trace<span class="token punctuation">.</span><span class="token function">Start</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
	<span class="token keyword">if</span> err<span class="token operator">!=</span><span class="token boolean">nil</span><span class="token punctuation">{</span>
		<span class="token function">panic</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">defer</span> trace<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li>
<p>测试程序输出trace信息：<code>go test -trace trace.out</code></p>
</li>
<li>
<p>可视化trace信息：<code>go tool trace trace.out</code></p>
</li>
</ul>
<h2 id="runtime">runtime<a class="anchor" href="#runtime">¶</a></h2>
<ul>
<li>Go的runtime没有虚拟机的概念</li>
<li>Runtime作为程序的一部分打包进二进制产物</li>
<li>Runtime随用户程序一起运行</li>
<li>Runtime与用户程序没有明显界限，直接通过函数调用</li>
<li>有一定屏蔽系统调用的能力</li>
<li>go的某些关键字在runtime中实现</li>
</ul>
<h3 id="能力">能力<a class="anchor" href="#能力">¶</a></h3>
<ul>
<li>内存管理能力</li>
<li>GC</li>
<li>并发（协程调度）</li>
</ul>
<h2 id="内存对齐">内存对齐<a class="anchor" href="#内存对齐">¶</a></h2>
<p>非内存对齐：内存的原子性与效率受影响。cpu在内存中操作按照整8个字长进行获取，当内存不对齐时，需要读取至少两个区域做拼接才行。</p>
<h3 id="对齐系数">对齐系数<a class="anchor" href="#对齐系数">¶</a></h3>
<ul>
<li>为了方便内存对齐，Go提供了对齐系数<code>unsafe.Alignof()</code></li>
<li>对齐系数的含义：变量的内存地址必须是被对齐系数整除</li>
<li>如果对齐系数为4，便是变量内存地址必须为4的倍数</li>
<li>内建类型对齐系数一般就是其sizeof的大小</li>
</ul>
<h3 id="结构体的内存对齐">结构体的内存对齐<a class="anchor" href="#结构体的内存对齐">¶</a></h3>
<p>结构体的内存对齐分为内部对齐和结构体之间对齐</p>
<ul>
<li>内部对齐：考虑成员大小和成员的对其系数
<ul>
<li>指的是结构体内部成员的相对位置（偏移量）</li>
<li>每个成员的偏移量是<strong>自身大小</strong>与其<strong>对齐系数</strong>较小值的倍数</li>
</ul>
</li>
<li>结构体长度填充：考虑自身对齐系数和系统字长。结构体通过增加长度，对齐系统字长</li>
<li>结构体长度是<strong>最大成员长度</strong>与<strong>系统字长</strong>较小的整数倍，这里的长度是结构体中分配长度的单位。</li>
</ul>
<p>基于上述原理，可以通过<strong>调节成员顺序</strong>，以实现节约空间。</p>
<p><strong>结构体的对齐系数是其成员的最大对齐系数。</strong></p>
<p>空结构体不要放在结构体的最后，在结构体中时，只会分配一个地址，并不占用空间。但是出现在结构体末尾时，为了避免空结构体地址影响后面的元素，需要补齐字长。</p>
<h2 id="系统设计">系统设计<a class="anchor" href="#系统设计">¶</a></h2>
<h3 id="面向错误的设计">面向错误的设计<a class="anchor" href="#面向错误的设计">¶</a></h3>
<p>隔离错误</p>
<p>冗余</p>
<p>逻辑结构重用，部署结构隔离</p>
<p>限流</p>
<p>慢响应：给阻塞操作设置超时时间</p>
<p>错误传递：断路器+服务降级</p>
<p>熔断</p>
<h3 id="面向恢复的设计">面向恢复的设计<a class="anchor" href="#面向恢复的设计">¶</a></h3>
<ul>
<li>注意僵尸进程，健康检查
<ul>
<li>池化资源耗尽</li>
<li>死锁</li>
</ul>
</li>
<li>拒绝单体系统</li>
<li>快速启动</li>
<li>无状态</li>
<li>在依赖服务不可用时，可以继续存活</li>
</ul>
<h2 id="Tip">Tip<a class="anchor" href="#Tip">¶</a></h2>
<p>Go语言很特别，没有对象，没有继承多态，没有泛型，没有try/catch。相反，有接口，函数式编程，CSP并发模型(goroutine+channel)。</p>
<p><code>go</code>语言仅支持封装，不支持继承和多态。没有<code>class</code>只有<code>struct</code>。面向对象使用接口来实现。</p>
<p><code>GOROOT</code>表示源码包所在路径。</p>
<p><code>GOPATH</code>表示开发者Go项目的默认路径。</p>
<h3 id="依赖包下载网络配置">依赖包下载网络配置<a class="anchor" href="#依赖包下载网络配置">¶</a></h3>
<p>由于国内特殊的网络环境，Go模块可能无法下载，但可以通过模块代理进行下载。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">go <span class="token function">env</span> <span class="token parameter variable">-w</span> <span class="token assign-left variable">GO111MODULE</span><span class="token operator">=</span>on
go <span class="token function">env</span> <span class="token parameter variable">-w</span> <span class="token assign-left variable">GOPROXY</span><span class="token operator">=</span>https://goproxy.cn,direct<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>或者基于系统的环境变量</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 一次性</span>
$ <span class="token builtin class-name">export</span> <span class="token assign-left variable">GO111MODULE</span><span class="token operator">=</span>on
$ <span class="token builtin class-name">export</span> <span class="token assign-left variable">GOPROXY</span><span class="token operator">=</span>https://goproxy.cn
<span class="token comment"># 永久</span>
$ <span class="token builtin class-name">echo</span> <span class="token string">"export GO111MODULE=on"</span> <span class="token operator">&gt;&gt;</span> ~/.profile
$ <span class="token builtin class-name">echo</span> <span class="token string">"export GOPROXY=https://goproxy.cn"</span> <span class="token operator">&gt;&gt;</span> ~/.profile
$ <span class="token builtin class-name">source</span> ~/.profile<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里的<code>.profile</code>文件可以改成<code>.zshrc</code>。</p>
<h3 id="Linux安装Go">Linux安装Go<a class="anchor" href="#Linux安装Go">¶</a></h3>
<ol>
<li>
<p>去<a target="_blank" rel="noopener" href="https://golang.org/dl/">官网</a>下载最新的Go安装包。</p>
</li>
<li>
<p><code>tar -zxvf &lt;tar.gz包&gt; -C /usr/local</code>该命令会在<code>/usr/local</code>路径下生成go文件夹</p>
</li>
<li>
<p><code>sudo mkdir /usr/local/gopath &amp;&amp; sudo chmod 777 /usr/local/gopath</code>这里存放go项目中的依赖</p>
</li>
<li>
<p>修改环境变量</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># sudo vi /etc/profile</span>
 <span class="token builtin class-name">export</span> <span class="token assign-left variable">GOROOT</span><span class="token operator">=</span>/usr/local/go
 <span class="token builtin class-name">export</span> <span class="token assign-left variable">GOPATH</span><span class="token operator">=</span>/usr/local/gopath
 <span class="token builtin class-name">export</span> <span class="token assign-left variable"><span class="token environment constant">PATH</span></span><span class="token operator">=</span><span class="token variable">$GOPATH</span>/bin:<span class="token variable">$GOROOT</span>/bin:<span class="token environment constant">$PATH</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li>
<p><code>source /etc/profile</code>生效配置</p>
</li>
</ol>
<h3 id="SOLID原则">SOLID原则<a class="anchor" href="#SOLID原则">¶</a></h3>
<p>在<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1">程序设计</a>领域， <strong>SOLID</strong>（<strong>单一功能、开闭原则、里氏替换、接口隔离</strong>以及<strong>依赖反转</strong>）是由<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/w/index.php?title=Robert_C._Martin&amp;action=edit&amp;redlink=1">罗伯特·C·马丁</a>在21世纪早期[<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/SOLID_(%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%AE%BE%E8%AE%A1)#cite_note-metz-presentation-2009-1">1]</a> 引入的<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E8%AE%B0%E5%BF%86%E6%9C%AF">记忆术</a><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E9%A6%96%E5%AD%97%E6%AF%8D%E7%BC%A9%E7%95%A5%E5%AD%97">首字母缩略字</a>[<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/SOLID_(%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%AE%BE%E8%AE%A1)#cite_note-ub-old-web-solid-2">2]</a>[<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/SOLID_(%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%AE%BE%E8%AE%A1)#cite_note-ub-solid-3">3]</a>，指代了<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B">面向对象编程</a>和<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%AE%BE%E8%AE%A1">面向对象设计</a>的五个基本原则。当这些原则被一起应用时，它们使得一个<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E7%A8%8B%E5%BA%8F%E5%91%98">程序员</a>开发一个容易进行<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E8%BB%9F%E9%AB%94%E7%B6%AD%E8%AD%B7">软件维护</a>和扩展的系统变得更加可能。[<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/SOLID_(%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%AE%BE%E8%AE%A1)#cite_note-metz-presentation-2009-1">1]</a> SOLID所包含的原则是通过引发编程者进行软件<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E6%BA%90%E4%BB%A3%E7%A0%81">源代码</a>的<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E4%BB%A3%E7%A0%81%E9%87%8D%E6%9E%84">代码重构</a>进行软件的<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E4%BB%A3%E7%A0%81%E5%BC%82%E5%91%B3">代码异味</a>清扫，从而使得软件清晰可读以及可扩展时可以应用的指南。SOLID被典型的应用在<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E6%B5%8B%E8%AF%95%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91">测试驱动开发</a>上，并且是<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E6%95%8F%E6%8D%B7%E5%BC%80%E5%8F%91">敏捷开发</a>以及<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/w/index.php?title=Adaptive_programming&amp;action=edit&amp;redlink=1">自适应软件开发</a>的基本原则的重要组成部分。</p>
<table>
<thead>
<tr>
<th style="text-align:center">首字母</th>
<th style="text-align:center">指代</th>
<th style="text-align:center">概念</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">S</td>
<td style="text-align:center"><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E5%8D%95%E4%B8%80%E5%8A%9F%E8%83%BD%E5%8E%9F%E5%88%99">单一功能原则</a></td>
<td style="text-align:center">认为“<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E5%AF%B9%E8%B1%A1_(%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A7%91%E5%AD%A6)">对象</a>应该仅具有一种单一功能”的概念。</td>
</tr>
<tr>
<td style="text-align:center">O</td>
<td style="text-align:center"><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E5%BC%80%E9%97%AD%E5%8E%9F%E5%88%99">开闭原则</a></td>
<td style="text-align:center">认为“软件应该是对于扩展开放的，但是对于修改封闭的”的概念。</td>
</tr>
<tr>
<td style="text-align:center">L</td>
<td style="text-align:center"><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E9%87%8C%E6%B0%8F%E6%9B%BF%E6%8D%A2%E5%8E%9F%E5%88%99">里氏替换原则</a></td>
<td style="text-align:center">认为“程序中的对象应该是可以在不改变程序正确性的前提下被它的子类所替换的”的概念。参考<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E5%A5%91%E7%BA%A6%E5%BC%8F%E8%AE%BE%E8%AE%A1">契约式设计</a>。</td>
</tr>
<tr>
<td style="text-align:center">I</td>
<td style="text-align:center"><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E6%8E%A5%E5%8F%A3%E9%9A%94%E7%A6%BB%E5%8E%9F%E5%88%99">接口隔离原则</a></td>
<td style="text-align:center">认为“多个特定客户端接口要好于一个宽泛用途的接口”[<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/SOLID_(%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%AE%BE%E8%AE%A1)#cite_note-martin-design-principles-5">5]</a> 的概念。</td>
</tr>
<tr>
<td style="text-align:center">D</td>
<td style="text-align:center"><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E4%BE%9D%E8%B5%96%E5%8F%8D%E8%BD%AC%E5%8E%9F%E5%88%99">依赖反转原则</a></td>
<td style="text-align:center">认为一个方法应该遵从“依赖于抽象而不是一个实例”[<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/SOLID_(%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%AE%BE%E8%AE%A1)#cite_note-martin-design-principles-5">5]</a> 的概念。 <a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5">依赖注入</a>是该原则的一种实现方式。</td>
</tr>
</tbody>
</table>
<h3 id="make与new">make与new<a class="anchor" href="#make与new">¶</a></h3>
<p>Go语言中 new 和 make 是两个内置函数，主要用来创建并分配类型的内存。在我们定义变量的时候，可能会觉得有点迷惑，不知道应该使用哪个函数来声明变量，其实他们的规则很简单，new 只分配内存，而 make 只能用于 slice、map 和 channel 的初始化。</p>
<p><strong>make 函数只用于 map，slice 和 channel，并且不返回指针。如果想要获得一个显式的指针，可以使用 new 函数进行分配，或者显式地使用一个变量的地址。</strong></p>
<p>Go语言中的 new 和 make 主要区别如下：</p>
<ul>
<li>make 只能用来分配及初始化类型为 slice、map、chan 的数据。new 可以分配任意类型的数据；</li>
<li>new 分配返回的是指针，即类型 *Type。make 返回引用，即 Type；</li>
<li>new 分配的空间被清零。make 分配空间后，会进行初始化；</li>
</ul>
<h4 id="new">new<a class="anchor" href="#new">¶</a></h4>
<p>在源码中new的函数描述如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// The new built-in function allocates memory. The first argument is a type,</span>
<span class="token comment">// not a value, and the value returned is a pointer to a newly</span>
<span class="token comment">// allocated zero value of that type.</span>
<span class="token keyword">func</span> <span class="token function">new</span><span class="token punctuation">(</span>Type<span class="token punctuation">)</span> <span class="token operator">*</span>Type<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>由上可知，<strong>new函数只接受类型这一个参数，返回一个指向该类型内存地址的指针。同时new函数会把分配的内存置为零，也就是类型的零值</strong>。</p>
<p>内置函数 new 会在编译期的 SSA 代码生成阶段经过 callnew 函数的处理，如果请求创建的类型大小是 0，那么就会返回一个表示空指针的 zerobase 变量，在遇到其他情况时会将关键字转换成 newobject：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">callnew</span><span class="token punctuation">(</span>t <span class="token operator">*</span>types<span class="token punctuation">.</span>Type<span class="token punctuation">)</span> <span class="token operator">*</span>Node <span class="token punctuation">{</span>
    <span class="token keyword">if</span> t<span class="token punctuation">.</span><span class="token function">NotInHeap</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">yyerror</span><span class="token punctuation">(</span><span class="token string">"%v is go:notinheap; heap allocation disallowed"</span><span class="token punctuation">,</span> t<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    <span class="token function">dowidth</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span>
    <span class="token keyword">if</span> t<span class="token punctuation">.</span><span class="token function">Size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">{</span>
        z <span class="token operator">:=</span> <span class="token function">newname</span><span class="token punctuation">(</span>Runtimepkg<span class="token punctuation">.</span><span class="token function">Lookup</span><span class="token punctuation">(</span><span class="token string">"zerobase"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        z<span class="token punctuation">.</span><span class="token function">SetClass</span><span class="token punctuation">(</span>PEXTERN<span class="token punctuation">)</span>
        z<span class="token punctuation">.</span>Type <span class="token operator">=</span> t
        <span class="token keyword">return</span> <span class="token function">typecheck</span><span class="token punctuation">(</span><span class="token function">nod</span><span class="token punctuation">(</span>OADDR<span class="token punctuation">,</span> z<span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span><span class="token punctuation">,</span> ctxExpr<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    fn <span class="token operator">:=</span> <span class="token function">syslook</span><span class="token punctuation">(</span><span class="token string">"newobject"</span><span class="token punctuation">)</span>
    fn <span class="token operator">=</span> <span class="token function">substArgTypes</span><span class="token punctuation">(</span>fn<span class="token punctuation">,</span> t<span class="token punctuation">)</span>
    v <span class="token operator">:=</span> <span class="token function">mkcall1</span><span class="token punctuation">(</span>fn<span class="token punctuation">,</span> types<span class="token punctuation">.</span><span class="token function">NewPtr</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">,</span> <span class="token function">typename</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span><span class="token punctuation">)</span>
    v<span class="token punctuation">.</span><span class="token function">SetNonNil</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> v
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>需要提到的是，哪怕当前变量是使用 var 进行初始化，在这一阶段也可能会被转换成 newobject 的函数调用并在堆上申请内存：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">walkstmt</span><span class="token punctuation">(</span>n <span class="token operator">*</span>Node<span class="token punctuation">)</span> <span class="token operator">*</span>Node <span class="token punctuation">{</span>
    <span class="token keyword">switch</span> n<span class="token punctuation">.</span>Op <span class="token punctuation">{</span>
    <span class="token keyword">case</span> ODCL<span class="token punctuation">:</span>
        v <span class="token operator">:=</span> n<span class="token punctuation">.</span>Left
        <span class="token keyword">if</span> v<span class="token punctuation">.</span><span class="token function">Class</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> PAUTOHEAP <span class="token punctuation">{</span>
            <span class="token keyword">if</span> prealloc<span class="token punctuation">[</span>v<span class="token punctuation">]</span> <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
                prealloc<span class="token punctuation">[</span>v<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">callnew</span><span class="token punctuation">(</span>v<span class="token punctuation">.</span>Type<span class="token punctuation">)</span>
            <span class="token punctuation">}</span>
            nn <span class="token operator">:=</span> <span class="token function">nod</span><span class="token punctuation">(</span>OAS<span class="token punctuation">,</span> v<span class="token punctuation">.</span>Name<span class="token punctuation">.</span>Param<span class="token punctuation">.</span>Heapaddr<span class="token punctuation">,</span> prealloc<span class="token punctuation">[</span>v<span class="token punctuation">]</span><span class="token punctuation">)</span>
            nn<span class="token punctuation">.</span><span class="token function">SetColas</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span>
            nn <span class="token operator">=</span> <span class="token function">typecheck</span><span class="token punctuation">(</span>nn<span class="token punctuation">,</span> ctxStmt<span class="token punctuation">)</span>
            <span class="token keyword">return</span> <span class="token function">walkstmt</span><span class="token punctuation">(</span>nn<span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token keyword">case</span> ONEW<span class="token punctuation">:</span>
        <span class="token keyword">if</span> n<span class="token punctuation">.</span>Esc <span class="token operator">==</span> EscNone <span class="token punctuation">{</span>
            r <span class="token operator">:=</span> <span class="token function">temp</span><span class="token punctuation">(</span>n<span class="token punctuation">.</span>Type<span class="token punctuation">.</span><span class="token function">Elem</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
            r <span class="token operator">=</span> <span class="token function">nod</span><span class="token punctuation">(</span>OAS<span class="token punctuation">,</span> r<span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
            r <span class="token operator">=</span> <span class="token function">typecheck</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> ctxStmt<span class="token punctuation">)</span>
            init<span class="token punctuation">.</span><span class="token function">Append</span><span class="token punctuation">(</span>r<span class="token punctuation">)</span>
            r <span class="token operator">=</span> <span class="token function">nod</span><span class="token punctuation">(</span>OADDR<span class="token punctuation">,</span> r<span class="token punctuation">.</span>Left<span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
            r <span class="token operator">=</span> <span class="token function">typecheck</span><span class="token punctuation">(</span>r<span class="token punctuation">,</span> ctxExpr<span class="token punctuation">)</span>
            n <span class="token operator">=</span> r
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            n <span class="token operator">=</span> <span class="token function">callnew</span><span class="token punctuation">(</span>n<span class="token punctuation">.</span>Type<span class="token punctuation">.</span><span class="token function">Elem</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>当然这也不是绝对的，如果当前声明的变量或者参数不需要在当前作用域外生存，那么其实就不会被初始化在堆上，而是会初始化在当前函数的栈中并随着函数调用的结束而被销毁。</p>
<p>newobject 函数的工作就是获取传入类型的大小并调用 mallocgc 在堆上申请一片大小合适的内存空间并返回指向这片内存空间的指针：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">newobject</span><span class="token punctuation">(</span>typ <span class="token operator">*</span>_type<span class="token punctuation">)</span> unsafe<span class="token punctuation">.</span>Pointer <span class="token punctuation">{</span>
    <span class="token keyword">return</span> <span class="token function">mallocgc</span><span class="token punctuation">(</span>typ<span class="token punctuation">.</span>size<span class="token punctuation">,</span> typ<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h4 id="make">make<a class="anchor" href="#make">¶</a></h4>
<p>make函数也是用于内存分配的函数，但是与new函数不同，<strong>它只适用于chan、map、slice的内存创建，返回类型是这三个类型本身，而不是它们的指针类型</strong>，因为这三种类型就是引用类型，没有鼻炎返回它们的指针。</p>
<p>在源码中make的函数描述如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// The make built-in function allocates and initializes an object of type</span>
<span class="token comment">// slice, map, or chan (only). Like new, the first argument is a type, not a</span>
<span class="token comment">// value. Unlike new, make's return type is the same as the type of its</span>
<span class="token comment">// argument, not a pointer to it. The specification of the result depends on</span>
<span class="token comment">// the type:</span>
<span class="token comment">// Slice: The size specifies the length. The capacity of the slice is</span>
<span class="token comment">// equal to its length. A second integer argument may be provided to</span>
<span class="token comment">// specify a different capacity; it must be no smaller than the</span>
<span class="token comment">// length, so make([]int, 0, 10) allocates a slice of length 0 and</span>
<span class="token comment">// capacity 10.</span>
<span class="token comment">// Map: An empty map is allocated with enough space to hold the</span>
<span class="token comment">// specified number of elements. The size may be omitted, in which case</span>
<span class="token comment">// a small starting size is allocated.</span>
<span class="token comment">// Channel: The channel's buffer is initialized with the specified</span>
<span class="token comment">// buffer capacity. If zero, or the size is omitted, the channel is</span>
<span class="token comment">// unbuffered.</span>
<span class="token keyword">func</span> <span class="token function">make</span><span class="token punctuation">(</span>t Type<span class="token punctuation">,</span> size <span class="token operator">...</span>IntegerType<span class="token punctuation">)</span> Type<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>通过上面的代码可以看出 make 函数的 t 参数必须是 chan（通道）、map（字典）、slice（切片）中的一个，并且返回值也是类型本身。</strong></p>
<p><img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/Go/Go%E5%AD%A6%E4%B9%A0/make_OMAKE.gif" alt="make_OMAKE.gif"></p>
<p>在编译期的类型检查阶段，Go语言其实就将代表 make 关键字的 OMAKE 节点根据参数类型的不同转换成了 OMAKESLICE、OMAKEMAP 和 OMAKECHAN 三种不同类型的节点，这些节点最终也会调用不同的运行时函数来初始化数据结构。</p>
<h3 id="空结构体">空结构体<a class="anchor" href="#空结构体">¶</a></h3>
<p>当结构体内部是空的时候，创建的对应大小为0，可以通过<code>unsafe.Sizeof()</code>查看大小。</p>
<p>在Go程序中所有的0-byte的地址都是用的同一个（不被包含在其他结构体中时），具体实现是对应了<code>malloc中的zerobase</code>变量。</p>
<p>这样的好处在于节约内存。</p>
<p>场景：</p>
<ul>
<li>当使用map实现hashset时，只使用了key，而不需要value，所有value都是空结构体的话，都指向一个地址</li>
<li>空结构体与channel结合可以当纯信号，实现空通道</li>
<li>实现集合类型</li>
<li>实现方法接收者，将方法组合起来，代表一个“分组”</li>
</ul>
<h3 id="GO环境变量">GO环境变量<a class="anchor" href="#GO环境变量">¶</a></h3>
<table>
<thead>
<tr>
<th>名称</th>
<th>作用</th>
<th>值</th>
</tr>
</thead>
<tbody>
<tr>
<td>GOARCH</td>
<td>用于指示GO编译器生成代码所针对的平台CPU架构</td>
<td>主要值是AMD64等，默认值是本机CPU架构</td>
</tr>
<tr>
<td>GOOS</td>
<td>用于指示GO编译器生成代码所针对的操作系统</td>
<td>主要值是Linux等，默认是本机的操作系统</td>
</tr>
<tr>
<td>GO11MODULE</td>
<td>决定了当前使用的构建模式是传统的GOPATH模式还是新引入的Go Module模式</td>
<td>在Go1.16版本Go Module构建模式默认开启，为on</td>
</tr>
<tr>
<td>GOCACHE</td>
<td>用于指示存储构建结果缓存的路径，这些缓存可能会被后续的构建所使用的</td>
<td>不同操作系统默认值不一样</td>
</tr>
<tr>
<td>GOMODCACHE</td>
<td>用于指示存放Go Module的路径</td>
<td>在不同的操作系统上不一样</td>
</tr>
<tr>
<td>GOPROXY</td>
<td>用来配置GO Module proxy</td>
<td>默认值为“https://proxy,golang.org,direct”</td>
</tr>
<tr>
<td>GOPATH</td>
<td>在传统GOPATH构建模式下，用于指示Go包搜索路径的环境变量</td>
<td></td>
</tr>
<tr>
<td>GOROOT</td>
<td>指示Go安装路径</td>
<td></td>
</tr>
</tbody>
</table>
<h3 id="安装多个go版本">安装多个go版本<a class="anchor" href="#安装多个go版本">¶</a></h3>
<ol>
<li>在PATH环境变量中设置成<code>export PATH=$PATH:/user/local/go/bin:~/go/bin</code></li>
<li><code>go get golang.org/dl/go.1.15.13</code></li>
<li><code>go1.15.13 </code></li>
</ol>
<h3 id="位运算">位运算<a class="anchor" href="#位运算">¶</a></h3>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">x <span class="token operator">&amp;^</span> <span class="token number">1</span> <span class="token operator">=</span> <span class="token number">0</span>
x <span class="token operator">&amp;^</span> <span class="token number">0</span> <span class="token operator">=</span> x<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h3 id="vscode">vscode<a class="anchor" href="#vscode">¶</a></h3>
<p>在vscode中执行test的代码可能会打印对应的log。原因是默认执行的是<code>go test</code>，这样的输出没有log，需要增加<code>-t</code> 的tag。</p>
<p>mac可以在<code>/Users/didi/Library/Application Support/Code/User/setting.json</code>中添加如下字段：</p>
<pre class="line-numbers language-json" data-language="json"><code class="language-json"><span class="token property">"go.testFlags"</span><span class="token operator">:</span> <span class="token punctuation">[</span>
        <span class="token string">"-v"</span>
    <span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h2 id="参考文献">参考文献<a class="anchor" href="#参考文献">¶</a></h2>
<ol>
<li><a target="_blank" rel="noopener" href="http://gopl.io/">《The Go Programming Language》</a></li>
<li>维基百科，<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/SOLID_(%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%AE%BE%E8%AE%A1)">SOLID (面向对象设计)</a>，2021</li>
<li><a target="_blank" rel="noopener" href="https://draveness.me/golang">Go 语言设计与实现</a></li>
<li><a target="_blank" rel="noopener" href="http://c.biancheng.net/view/5722.html">Go语言make和new关键字的区别及实现原理</a></li>
<li><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/a530f506beac">大话图解golang map</a></li>
<li><a target="_blank" rel="noopener" href="https://halfrost.com/go_map_chapter_one/#toc-0">如何设计并实现一个线程安全的 Map ?</a></li>
<li><a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000040473355">golang 系列：mutex 详解</a>，2021</li>
</ol>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">不二</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://buerlog.top/2019/12/01/cheng-xu-she-ji/go/go-xue-xi/">http://buerlog.top/2019/12/01/cheng-xu-she-ji/go/go-xue-xi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">不二</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Go/">
                                    <span class="chip bg-color">Go</span>
                                </a>
                            
                                <a href="/tags/Book/">
                                    <span class="chip bg-color">Book</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/12/08/jing-yan-zong-jie/centos7-chu-shi-hua-an-zhuang-bu-zou/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/经验总结/centos.png" class="responsive-img" alt="CentOS7初始化安装步骤">
                        
                        <span class="card-title">CentOS7初始化安装步骤</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-12-08
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%BB%8F%E9%AA%8C%E6%80%BB%E7%BB%93/" class="post-category">
                                    经验总结
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Python/">
                        <span class="chip bg-color">Python</span>
                    </a>
                    
                    <a href="/tags/Linux/">
                        <span class="chip bg-color">Linux</span>
                    </a>
                    
                    <a href="/tags/CentOS/">
                        <span class="chip bg-color">CentOS</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/12/01/qian-ru-shi/sg90-duo-ji-kong-zhi/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@src/source/_posts/PageImg/嵌入式/pcb.jpg" class="responsive-img" alt="sg90舵机控制">
                        
                        <span class="card-title">sg90舵机控制</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-12-01
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F/" class="post-category">
                                    嵌入式
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E6%A0%91%E8%8E%93%E6%B4%BE/">
                        <span class="chip bg-color">树莓派</span>
                    </a>
                    
                    <a href="/tags/Arduino/">
                        <span class="chip bg-color">Arduino</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 不二博客<br />'
            + '文章作者: 不二<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="song"
                   id="1901371647"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2018-2023</span>
            
            <span id="year">2018</span>
            <a href="/about" target="_blank">不二</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">263.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2018";
                    var startMonth = "5";
                    var startDate = "25";
                    var startHour = "17";
                    var startMinute = "20";
                    var startSecond = "53";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/weiyouwozuiku" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:weiyouwozuiku@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1104891151" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1104891151" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/he-he-9-35-47" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/he-he-9-35-47" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <script src='https://unpkg.com/mermaid@8.14.0/dist/mermaid.min.js'></script>
    <script>
      if (window.mermaid) {
        mermaid.initialize({theme: 'forest'});
      }
    </script>
  

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/materialize/materialize.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/aos/aos.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?943a68f473d421f2d98228f74edc63d0";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    
    <script async src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="150"
        src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="https://cdn.jsdelivr.net/gh/weiyouwozuiku/weiyouwozuiku.github.io@master/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
